Checkboxes are one of the several types of input fields we use very commonly to allow users to interact with web pages and typically POST data to a backend, by checking any box that applies to a given situation.
As opposed to Radio Buttons (which belong to Radio Groups) - checkboxes belonging to a single group aren't mutually exclusive so a user can select multiple boxes that apply. You should keep this in mind when checking whether any options are selected.
In this guide, we'll take a look at how to check if a checkbox is checked in jQuery - a popular library for JavaScript, and Vanilla JavaScript.
element.checked
Let's start out with a simple Checkbox setup:
<h1>Check if Checkbox is Checked</h1>
<p>Have you taken this test before?</p>
<input type="checkbox" id="takenBefore" placeholder="Yes">
<label for="takenBefore">Yes</label>
<button id="button"> Check Checkbox </button>
In pure JavaScript - checking if a Checkbox is checked is as easy as accessing the checked
field, represented by a boolean:
// Get relevant element
checkBox = document.getElementById('takenBefore');
// Check if the element is selected/checked
if(checkBox.checked) {
// Respond to the result
alert("Checkbox checked!");
}
However, this code will only ever run if you specifically run it. For instance, you could run it when the user submits a form or wishes to proceed to the next page as a validation step. Validation isn't commonly done this way, and typically delegated to libraries that are more robust. More commonly, you want to react to the checkbox to change something on the page - such as providing other input options.
In these cases, you'll want to add an event listener to the button, and let it listen to events, such as being clicked. When such an event occurs - you can decide to respond to the event:
checkBox = document.getElementById('takenBefore').addEventListener('click', event => {
if(event.target.checked) {
alert("Checkbox checked!");
}
});
In this setup - the code is constantly waiting and listening to events on the element! Now as soon as someone clicks the Checkbox, your alert()
method will execute. This time, however, to obtain the checkBox
element, we procure it from the event
instance, as the target
of that event.
When you open the page up in a browser, and click the button, you'll be greeted with:
$('#element')[0].checked
Note: jQuery is a popular JavaScript library, present in many projects around the world. Due to its light weight and features that expand the scope of JavaScript's built-in capabilities - it's become a staple. Not surprisingly - it can be used to check whether a Checkbox is selected or not.
We can use jQuery's selector syntax instead of pure JavaScript's to simplify both the selection of the element and the event listener attached to it.
You can import jQuery in your page via a Content Delivery Network (CDN). You can use jQuery's own CDN for importing the library as well.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous">
</script>
To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ([0]
) and use the built-in checked
property:
let isChecked = $('#takenBefore')[0].checked
console.log(isChecked);
Here, we'd be testing if the takenBefore
checkbox is checked, by accessing it via jQuery's selector, and using the innate checked
field as before.
Alternatively, you can define a listener that detects a change:
$('#takenBefore').change(function() {
alert('Checkbox checked!');
});
This code is much simpler, but performs in much the same way as the pure JS solution! Clicking the checkbox will trigger an alert as before:
$('#element').is(':checked'))
Instead of checking via the built-in checked
property - we can offload the logic to the is()
method. The is()
method is a general method that can be used for many purposes - and returns a true
/false
based on the comparison criteria. The :checked
selector was specifically made for checking whether a radio button or checkbox element had been selected or not.
So, if you combine these together, it's easy to check whether a checkbox is(':checked')
:
let isChecked = $('#takenBefore').is(':checked');
console.log(isChecked); // true (if checked at the time)
$('#element').prop("checked")
In earlier versions of jQuery - attr()
was used to access and manipulate fields of elements. In newer versions, the method was replaced with prop()
. It can work as a getter/setter for properties of elements, and in our case - as a wrapper for getting the checked
property of an element.
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
let isChecked = $('#takenBefore').prop('checked');
console.log(isChecked); // true (if checked at the time)
is() vs prop()?
So, what's the difference between
is()
andprop()
in this context?
Both methods appear to work in much the same way from our perspective. So, what's the difference?
is()
has a bit more overhead processing and parsing than prop()
. Even considering the fact that prop()
doesn't just access the property and does some validation, it's more performant when it comes to processing a large number of inputs, say, in a loop.
On the other hand - is()
always returns a boolean
value, whereas prop()
just returns the underlying property's type. You can't guarantee that something else sneaked in, and your code may fail at runtime if you don't use prop()
properly. is()
also semantically indicates the return value - a boolean
, which makes it a more readable option.
Conclusion
In this short guide, we've taken a look at how to check whether a checkbox is checked with JavaScript and jQuery.
We've used the checked
property - directly and indirectly, followed by the is()
and prop()
methods, as well as taken a quick look as to which you could prefer.