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".

2 Answers

1
Rajan On Best Solutions

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

1
Dupinder Singh On

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);
           }
     });        
  });