Last Updated: February 25, 2016
·
1.263K
· travishaynes

Why are there so many songs about programming?

Okay, so maybe there really aren't any songs about programming, but there are a lot of ways to approach even the simplest of problems when you're programming. This article discusses just one: Checking the state of an HTML check-box using JavaScript.

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.

The problem I ran into was using JavaScript to check the state of the check-box. I mean, it's not like it's a complicated thing to do. But there are so many ways to do it, when you really start thinking about it.

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[0].checked

checkbox.prop("checked")

checkbox.attr("checked") === "checked"

typeof checkbox.attr("checked") !== "undefined"

checkbox.attr("checked")

checkbox.is(":checked")

$("#the_checkbox:checked").length

$("#the_checkbox:checked").length > 0

!!$("#the_checkbox:checked").length

// 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.