To check if a checkbox is checked using jQuery, the simplest way is to use is() combined with “:checked”.
$('#checkbox').is(':checked');
Let’s say I have the following HTML:
If I want to see if the checkboxes are checked, we can do the following:
var isChecked1 = $('#checkbox-1').is(':checked');
console.log(isChecked1); // false
var isChecked = $('#checkbox-2').is(':checked');
console.log(isChecked2); // true
If you are using WordPress, don’t forget to change the $ to jQuery as below:
var isChecked1 = jQuery('#checkbox-1').is(':checked');
var isChecked2 = jQuery('#checkbox-2').is(':checked');
Check if Checkbox is Checked Using jQuery When Checkbox is Clicked
Many times when creating a web page and the user experience, we want to check certain conditions based on an interaction with another element on the web page.
We can check if a checkbox is checked using jQuery very easily by combining the is() method with a click event.
Let’s say we have the following HTML code and we want to display the checked value of our checkbox in the span below:
Click the Checkbox to Update the "Checked" status of Checkbox
The value of the checkbox is: .
We can utilize both the jQuery click() method and jQuery is() method to find the value of the checkbox. Then we will change the text of the span and display true or false.
Below is the Javascript code which will allow us to see if our checkbox is checked and then display that value.
$('#checkbox-1').click(function(){
$("#div1 p span").text($('#checkbox-1').is(':checked'));
});
The final code and output for this example of how to check if a checkbox is checked using jQuery and Javascript is below:
Code Output:
Click the Checkbox to Update the “Checked” status of Checkbox
The value of the checkbox is: false.
Full Code:
Click the Checkbox to Update the "Checked" status of Checkbox
The value of the checkbox is: .
<script>
$('#checkbox-1').click(function(){
$("#div1 p span").text($('#checkbox-1').is(':checked'));
});
</script>
Using the jQuery prop() method to Check if a Checkbox is Checked
Another way we can check if a checkbox is checked with jQuery is using the jQuery prop() method.
Let’s say we have the same HTML as above:
Click the Checkbox to Update the "Checked" status of Checkbox
The value of the checkbox is: .
Below is the Javascript code which will allow us to see if our checkbox is checked using the prop() method.
$('#checkbox-1').click(function(){
$("#div1 p span").text($('#checkbox-1').prop('checked'));
});
The final code and output for this example of how to check if a checkbox is checked using jQuery and Javascript is below:
Code Output:
Click the Checkbox to Update the “Checked” status of Checkbox
The value of the checkbox is: false.
Full Code:
Click the Checkbox to Update the "Checked" status of Checkbox
The value of the checkbox is: .
Hopefully this article has been useful for you to understand how to check if a checkbox is checked using jQuery.