In this tutorial, we explain how to check if the checkbox is checked using JQuery.
We will explain many alternatives in this tutorial, we recommend to try all of them to learn more about JQuery. An input of the type checkbox is usually defined by the following HTML:
<input type="checkbox" id="conditions"/> I agree the conditions
In the following examples, we are going to select the input control by its id, "conditions". We will also explain how to set the checkbox value.
Using the prop method
Using the new property method will return true or false.
$('#conditions').prop('checked');
Using the new property method:
if($('#conditions').prop('checked')) {
console.log("checked");
} else {
console.log("unchecked");
}
In the example we use jQuery to get checkbox value and print a console message if checked. For this solutions, you are required to use jQuery 1.6 or newer.
Using javascript without libs
The checked
property of a checkbox input will return the checked
state of the element.
As an example:
if(document.getElementById('conditions').checked) {
$("#inputName").show(); }
else { $("#inputName").hide();
}
Using the JQuery's is()
You can also use jQuery's is(). Here we show a simple example on how to use it. Note the double dots on the parameter:
if($("#conditions").is(':checked')) {
console.log("checked");
} else {
console.log("unchecked");
}
How to set a checkbox value
Using attr to get checked
Another approach is to use attr of a jquery object:
if ($("#conditions").attr("checked")) {
console.log("Checked")
} else {
console.log("Unchecked");
}
Using the checked property as an attribute
You can also use the attr to the set value of the checkbox:
$("conditions").attr("checked",true);
Using the jquery toggle to a checkbox
Using toggle
could result in a simple code:
$("#conditions").toggle(this.checked);