简体   繁体   中英

Javascript addClass or removeClass not working in subclass after ajax call

I have an ajax script that inserts a value if it is not in the database and removes the value if it is already there, and returns 1 or 0 accordingly, based on the return value it adds or removes a class in the existing button.

I have tried with find() to take the subclass value but still it is not working.

<form method="post" class="wish" action="process.php">
  <input type='hidden' id='value' name='value' value='1'>
  <button type="submit" class="card-fox list active" >fan</button>
</form>

This line has active I want it to be added if it is not there and remove if it is there.

below is the ajax:

$(document).ready(function (e) {
  $(".wish").on('submit', (function (e) {
    e.preventDefault();
    $.ajax({
      url: "process.php",
      type: "POST",
      data: new FormData(this),
      contentType: false,
      cache: false,
      processData: false,
      success: function (data) {
        if (data == 1) {
          $(".list", this).addClass("active");
        }
        if (data == 2) {
          $(".list", this).removeClass("active");
        }
      },
      error: function (e) {}
    });
  }));
});

the problem is that although the ajax script is being executed and everything else is working, the active class is neither adding or removing.

The this in your ajax success function is not the form.
You can set the context of the ajax call to the for to address this.

$.ajax({
    context: this, //<- this this is the form, and tells jQuery to set the this of its callbacks to the form

Use:

$(".wish").find('button').addClass("active");
$(".wish").find('button').removeClass("active");

Or:

//when form is submit, make a copy of this
let self = this;

//send ajax
//in success ajax
$(self).find('button').addClass("active");

Greetings!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM