jQuery and checkboxes

Using a javascript library like jQuery can speed up your development. However sometimes you might hit a wall when doing simple things “the jQuery way”.

A common example is working with checkboxes. How do we determine if the checkbox is checked or not? How do check the checkbox automatically?

In regular javascript, it’s quite straight forward:

var chk = document.getElementById("myCheckbox");
if (chk.checked) {
  // the checkbox is checked..
}

In jQuery, we cannot check the “checked” property of the element, since the element is actually a jQuery object.

var chk = $("#myCheckbox");
alert(chk.checked); //undefined!

Though the jQuery object does not have a checked property, the checkbox itself still has the “checked” attribute. So we can test if the attribute is true or false. Luckily, jQuery has an is() function which does just that.

var chk = $("#myCheckbox");
if (chk.is(":checked")) {
  // the checkbox is checked..
}

It’s very simple but just takes a little different thinking.

To “check” the checkbox using jQuery, you would again do it using the “checked” attribute of the input element.

var chk = $("#myCheckbox");
chk.attr("checked", true);

That’s all there is to it, really. Hopefully this little tip will help you out. Happy programming!

About the Author