How to Determine Whether Radio buttons and Checkboxes are Checked using jQuery

Leave a Comment

While the val() function is helpful for getting the value of any form element, for some fields, the value is important only if the visitor has selected the field. For example, radio buttons and checkboxes require visitors to make a choice by selecting a particular value. You saw on page 260 how you can use the :checked filter to find checked radio buttons and checkboxes, but once you find it, you need a way to determine the status of a particular button or box.

In HTML, the checked attribute determines whether a particular element is checked. For example, to turn on a box when the web page is loaded, you add the checked attribute like this for XHTML:
<input type="checkbox" name="news" id="news" checked="checked" />

And this for HTML5:
<input type="checkbox" name="news" id="news" checked>

Since checked is an HTML attribute, you can easily use jQuery to check the status of the box like this:
if ($('#news').attr('checked')) {
// the box is checked
} else {
// the box is not checked
}

The code $(‘#news’).attr(‘checked’) returns the value true if the box is checked. If it’s not, it returns the value undefined, which the JavaScript interpreter considers the same as false. So this basic conditional statement lets you perform one set of tasks if the box is turned on or a different set of tasks if the box is turned off.

The checked attribute applies to radio buttons as well. You can use the attr() function in the same way to check whether the radio button’s checked attribute is set.

0 comments:

Post a Comment