jQuery val() and checkboxes

I can’t think of a good reason why it
wouldn’t return true or false. Failing
that, at least return “on” only when
checked, and an empty string when not.
Failing that, at least always return
an empty string, given that checkboxes
have no value attribute!

Checkboxes do have a value attribute. It’s quite common to use it in eg. multi-checkboxes in forms, for example:

<input type="checkbox" name="foo[]" value="1" />
<input type="checkbox" name="foo[]" value="2" />

Then when user submits the form, the server can parse which of the checkboxes were checked by checking the values of the foo[] array. The value of the checkbox does not change whether it is checked or not; the browser simply does not send the values of unchecked checkboxes to the server. If you do eg. $('#your-form').serialize()in jQuery, it should work similarly; it shouldn’t include values of unchecked checkboxes. If you omit the value from checkbox, it simply defaults to on.

If you want to check whether an individual checkbox is checked or not in jQuery, the best most descriptive way is to do $(this).is(':checked')

Leave a Comment