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:
You wouldn’t really expect it, but both of these return “on” when you get the
Now say you flipped them by unchecking checkbox1 and checking checkbox2. Same thing:
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
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.