How do I check if a checkbox is checked in jQuery?

Contents [hide]

1. Introduction

It is a common concern when using jQuery in web development: How do I check if a box is checked? This task can be done in multiple ways. Examples are provided to illustrate the process.

2. Using the DOM property “checked”

A checkbox belongs to the HTMLInputElement class and has a property called “checked” which is set to true if it is selected.

See the following example. This Refers the checkbox element DOM element whose “Checked” is currently being checked. The function outputs information about the current state of check-boxes.

$('#check').change(function(ev) {
   if ( this.checked ) console.log('checked');
   else console.log('not checked');
});

This example is not using any jQuery specific features. However, it can be written as follows (without jQuery).

document.getElementById('check').addEventListener('change', function() {
   if ( this.checked ) console.log('checked');
   else console.log('not checked');
});

3. Using jQuery is(‘:checked’)

jQuery supports the.is(‘checked’), method, which can be used in these ways:

$('#check').change(function(ev) {
    if ( $(this).is(':checked') ) console.log('checked');
    else console.log('not checked');
});

This method will check if any of the check-boxes matches the jQuery selection-or. This HTML creates many check-boxes using the same type.

<label class="checkbox-inline">
<input id="checkboxRed" type="checkbox"
   class="colorCheck"
   value="red"> Red
</label>
<label class="checkbox-inline">
<input id="checkboxGreen" type="checkbox"
   class="colorCheck"
   value="green"> Green
</label>
<label class="checkbox-inline">
<input id="checkboxRed" type="checkbox"
   class="colorCheck"
   value="blue"> Blue
</label>

Checkbox collection

If at LEAST one is checked, the code will print true.

$('.colorCheck').change(function(ev) {
    console.log('any checked? ' + $('.colorCheck').prop(':checked'));
});

4. Using jQuery .prop()

Another way to check the state using JQuery is to use the “prop()” method.

$('#check').change(function(ev) {
    if ( $(this).prop('checked') ) console.log('4. checked');
    else console.log('4. not checked');
});

Make sure you check whether multiple check boxes use the same construct.

$('.colorCheck').change(function(ev) {
    console.log('any checked? ' + $('.colorCheck').prop('checked'));
});

5. Using jQuery “checked” Selector

If you have multiple checkboxes related to each other, you can compile a list by doing the following:

var boxes = $('.colorCheck:checked');
boxes.each(function(i, chkbox) {
  // process each checked box here
});

// How many are checked
console.log('Checked #' + boxes.length);

Conclusion

We discussed in this article different methods for checking the status and functionality of check-boxes: using jQuery with or without. Depending upon your specific circumstances, you might prefer one method over the next.

Exit mobile version