views:

63

answers:

2

Hi all

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.

+2  A: 

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

lomaxx
+1 for annoying little buggers :D
Here Be Wolves
+5  A: 

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() : '' }
David Hedlund
The latter is how I tend to deal with checkboxes when using jQuery.
ayaz
Thanks very much. Good solution, well described.
tonyyeb