I started thinking about this the other day while I was working on a Rails application that had a couple of preferences for a User model. Since there were only two options, and they were both boolean values, I decided to use AJAX to update the preferences immediately after the user checks one of the boxes. That way there's no need for a page refresh, or anything like that.
For example, using jQuery, you could check the value of the "checked" attribute, like this:
$("#the_checkbox").attr("checked") === 'checked'
However, in HTML, it doesn't matter what value is in the checked attribute, as long as it has content. So, really, checking if the value is 'checked' might not always work. I mean, it should. But as a programmer, I don't like to leave things to chance like that. So this would be a more fool-proof example:
typeof($("#the_checkbox").attr("checked")) !== 'undefined'
But, wait! What if the check-box has a checked attribute, but it's empty, like this?
<input type="checkbox" checked>
Personally, I have no idea. But I do know that in Chrome and Firefox, those browsers at least see that as a checked input, and if you use jQuery to check the value of the "checked" attribute, it says it equals "checked", even though it is in fact empty. But I don't how the nearly hundreds of variations of other browsers and versions (here's looking at you, IE!) out there would see that.
Okay, so this post is going to go on forever if I list all the individual ways to check the state of a checkbox in JS, and go into each one individually. So, here's a list of just some the ways I could think of to do it:
// First, find the checkbox using jQuery:
var checkbox = $("#the_checkbox");
// and then see if it's checked:
checkbox.attr("checked") === "checked"
typeof checkbox.attr("checked") !== "undefined"
$("#the_checkbox:checked").length > 0
// or, by accessing the DOM directly:
var checkbox = document.getElementById("the_checkbox"),
checked = checkbox.checked;
So the question is, and I've seen this asked a lot, what is the best way to check the state of a check-box in JS? Is there really a "best" way to do this?
You tell me.