Jibeji
Jibeji

Reputation: 473

Multiple checkboxes with Ajax strange behavior

I have a form with many checkboxes, and a PHP page is called for updating the database on each click.

HTML

<form>
   <input type="checkbox" name="status1" id="event_status1" value="1" >
   <input type="checkbox" name="status2" id="event_status2" value="1" >
   <input type="checkbox" name="status3" id="event_status3" value="1" >
</form>

JQuery

  $('input:checkbox').change(function(e) {
     e.preventDefault();
     var isChecked = $("input:checkbox").is(":checked") ? 1:0; 
     $.ajax({
           type: 'POST',
           url: "admin-ajax.php",
           data: { event_status:$("input:checkbox").attr("id"), status:isChecked},
           success: function (response) {
              console.log(response);
           }
     });        
  });

It works well when I check/uncheck each checkbox individualy.

If I check the 3 boxes, the last I have checked won't send "0" status if I uncheck it but wil always send "1".

Upvotes: 0

Views: 90

Answers (2)

Rajan
Rajan

Reputation: 1497

You have to use the input dom whose change event is triggered not this one

$("input:checkbox")

You have to do something like this:

$('input:checkbox').change(function (e) {
    e.preventDefault();
    var self = $(this);
    var isChecked = self.is(":checked") ? 1 : 0;
    $.ajax({
        type:    'POST',
        url:     "admin-ajax.php",
        data:    {event_status: self.attr("id"), status: isChecked},
        success: function (response) {
            console.log(response);
        }
    });
});

If you want to prepare the ajax data object outside of $.ajax you can do like this:

$('input:checkbox').change(function (e) {
    e.preventDefault();
    var data = {event_status: $(this).attr("id"), status: +$(this).is(":checked")};
    $.ajax({
        type:    'POST',
        url:     "admin-ajax.php",
        data:    data,
        success: function (response) {
            console.log(response);
        }
    });
});

Note: + in +$(this).is(":checked") converts boolean to Number, false becomes 0, and true becomes 1

Upvotes: 1

Dupinder Singh
Dupinder Singh

Reputation: 7769

I think the issue is with third line:

 var isChecked = $("input:checkbox").is(":checked") ? 1:0; 

You use jquery selector $('input:checkbox') which will return random checkbox from whole HTML DOM Structure, this will not return your clicked Checkbox, So the solution is use this.

So the code will look like this:

 $('input:checkbox').change(function(e) {
     e.preventDefault();
     var isChecked = $(this).is(":checked") ? 1:0; 
     var eleId = $("this").attr("id");
     $.ajax({
           type: 'POST',
           url: "admin-ajax.php",
           data: { event_status:eleId, status:isChecked},
           success: function (response) {
              console.log(response);
           }
     });        
  });

Upvotes: 1

Related Questions