jQuery And Checkbox Values

I rarely use checkboxes and radio buttons. Perhaps because of that I forgot this little rookie error.

For the intents and purposes below assume the following HTML:

<p>
<label for="checkbox1">Checkbox 1</label>
<input type="checkbox" id="checkbox1" checked="checked"/>
</p>
 
<p>
<label for="checkbox2">Checkbox 2</label>
<input type="checkbox" id="checkbox2"/>
</p>

You wouldn’t really expect it, but both of these return “on” when you get the val():

$(‘#checkbox1′).val(); // returns "on"
$(‘#checkbox2′).val(); // returns "on"

Now say you flipped them by unchecking checkbox1 and checking checkbox2. Same thing:

$(‘#checkbox1′).val(); // returns "on"
$(‘#checkbox2′).val(); // returns "on"

Now reload the page, so one is checked and two is not checked. Try again this time using .attr('checked');. That also doesn’t work, but that makes sense. jQuery 1.6’s release notes even explain it:

Before jQuery 1.6, .attr(“checked”) returned the Boolean property value (true) but as of jQuery 1.6 it returns the actual value of the attribute (an empty string), which doesn’t change when the user clicks the checkbox to change its state

The best way I’ve found to get a checkbox value is to use the is() method:

$(‘#checkbox1′).is(‘:checked’) // returns true

As to why val() doesn’t check the type of node and do this for me automatically? I’m not entirely sure. I’m assuming backwards compatibility. I suspect I’m not the only one who keeps forgetting this little caveat.

Leave a Reply

Your email address will not be published. Required fields are marked *

Connect with Facebook

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>