Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using checkboxes with Jquery AJAX

I am using JQuery for some AJAX functionality. But when is pass the value of a checkbox, the value is show regardless of whether the checkbox is ticked or not. Here is my code:

$(document).ready(function(){ 
  $('#submitform').click(function(){
    $.ajax({
      type: "POST",
      url: "abs_newabs_check.asp",
      data: { allday: $("#allday").val() },
      success: callback
    });
  });
});

function callback(data, status)
{
    $("#ajaxdiv").html(data);
}

What am I doing wrong? Any help appreciated. Thanks.

like image 352
tonyyeb Avatar asked Aug 17 '26 14:08

tonyyeb


2 Answers

The value of your checkbox, as accessed by val() will always be corresponding to the value property of the input. Which is always set, regardless of the checkbox's checked-state. What you want to check for is checked property:

{ allday: $('#allday').is(':checked') }

or if you really do want to pass the value, when it's checked:

{ allday: $('#allday').is(':checked') ? $('#allday').val() : '' }
like image 80
David Hedlund Avatar answered Aug 19 '26 02:08

David Hedlund


Checkboxes are annoying little buggers. You have to actually check if the "checked" attribute is checked on the checkbox and if it is, only then do you want to apply the value.

So if you have a checkbox

<input type="checkbox" name="sports" value="soccer"  />

you want to check that the checked attribute has been set on it

<input type="checkbox" checked="yes" name="sports" value="soccer"  />

The value will always be the same, it's the state that changes

like image 21
lomaxx Avatar answered Aug 19 '26 03:08

lomaxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!