In this tutorial, we are going to learn how to check if a checkbox is checked in jQuery. Let’s say we have a checkbox and button.
<input id="toc" type="checkbox">
<label for="toc"> Terms & Conditions</label><br>
<button id="btn">Check</button>
When the button is clicked, it will check if the check box is checked or not.
$(document).ready(function(){
$("#btn").click(function(){
var toc = $('#toc').is(':checked');
if(toc === true){
alert("Checkbox is checked");
}else{
alert("Checkbox is not checked");
}
});
});
In the above code, we are using .is()
to check the checkbox property is checked or not by passing the value :checked
. It will return either true
or false
based on checked property.
How to get checked item from array of checkboxes with the same name?
Suppose we have multiple checkboxes with the same name i.e “color”. Now we want to check which checkbox is checked. So let’s check the example.
<input id="red" name="color" type="checkbox" value="red">
<label for="red">Red</label><br>
<input id="green" name="color" type="checkbox" value="green">
<label for="green">Green</label><br>
<input id="blue" name="color" type="checkbox" value="blue">
<label for="blue">Blue</label><br>
<button id="btn">Check</button>
JQuery:
$(document).ready(function(){
$("#btn").click(function(){
var colors = $('input[name=color]:checked');
colors.each(function(){
alert($(this).val());
});
});
});
In the above example, we store the value of the checked item in a variable i.e. var colors = $('input[name=color]:checked');
. By using each()
, we loop through each item and show the checked value.
How to store selected checkboxes into array by using jQuery?
There are two ways we can do this. The first method is just like the above method. Instead, make an alert()
, we have to store the value to an array.
$(document).ready(function(){
var checkArray = [];
$("#btn").click(function(){
var colors = $('input[name=color]:checked');
colors.each(function(){
checkArray.push($(this).val());
});
console.log(checkArray);
});
});
Output:
["red","blue"]
In the second method, we are using get()
.
$(document).ready(function(){
$("#btn").click(function(){
var colors = $('input[name=color]:checked').map(function(){
return $(this).val();
}).get();
console.log(colors);
});
});