2

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 Answers 2

7

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() : '' }
Sign up to request clarification or add additional context in comments.

2 Comments

The latter is how I tend to deal with checkboxes when using jQuery.
Thanks very much. Good solution, well described.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.