Getting and Setting a Checkbox Value in jQuery

Written by James Mansson on October 12, 2013 Categories: jQuery

Getting and setting a checkbox value is a common task in jQuery, which is simple to achieve when you know how.

Suppose we have a checkbox with an ID of active. To get the value of this checkbox as a 1 or 0 (checked or unchecked), we can use the following jQuery code:

var value = $("#active").is(":checked") ? 1: 0

To set the checkbox as checked or unchecked, there are two methods. The first works in all versions of jQuery, the second in newer versions (1.6 or later).

The older method sets the checkbox as checked by:

$("#active").attr("checked", "checked")

and sets it as unchecked by:

$("#active").removeAttr("checked")

The newer method uses:

$("'#active").prop("checked", isChecked)

where isChecked is true or false.

No Comments on Getting and Setting a Checkbox Value in jQuery

Leave a Reply

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