In this article i will show you multiple way to check or validate if a checkbox is checked or not. Also i will show you to check a checkbox programmatically. In the post we will learn all possibilities to validate a checkbox and how we can check a checkbox using jQuery.
There is multiple way to check weather a checkbox is checked or not , so here are the example of jQuery checkbox checked
Using jQuery attr()
function, attr()
function is used to get the attribute of any element. it accepts two parameters first is name of attribute and other one is value of attribute.
If we pass only first parameter then it will return the value of attribute and both parameters are passed then it will set the attribute value.
$(element).attr('checked'); // will return string checked or null
Using jQuery prop() function
$(element).prop('checked'); // will return boolean true / false
Using jQuery i
s() function
$(element).is(':checked'); // will return boolean true / false
Let’s take an example of jQuery checkbox checked
Example 1 : check jQuery checkbox checked or not
In this example i will use simple checkbox and html to show their value as below
<input type="checkbox" id="isSelected" checked />
<div>Prop value : <span id="output-prop"></span></div>
<div>Attr value : <span id="output-attr"></span></div>
<div>Is value : <span id="output-is"></span></div>
<button id="mark-checked">Set Checked</button>
Here we used a checkbox with id isSelected
and also the output dick to show the values and then JavaScript
<script>
$(function () {
$('#isSelected').click(function () {
$('#output-prop').html($(this).prop('checked'));
$('#output-attr').html($(this).attr('checked'));
$('#output-is').html($(this).is(':checked'));
});
$('#isSelected').change(function () {
$('#output-prop').html($(this).prop('checked'));
$('#output-attr').html($(this).attr('checked'));
$('#output-is').html($(this).is(':checked'));
});
$('#mark-checked').click(function () {
var isChecked = $('#isSelected').prop('checked');
$('#isSelected').prop('checked', !isChecked);
$('#isSelected').trigger('change');
});
});
</script>
Here we registered 3 methods one for on click of checkbox, second on change of checkbox and third to check the checkbox programatically.
Live Preview :
How to check checkbox programmatically?
In the above example if you see we have registered a button and the click event on the button the programmatically check or uncheck the box. so create a button
<button id="mark-checked">Set Checked</button>
and then register click event to set the value of checkbox
$('#mark-checked').click(function () {
var isChecked = $('#isSelected').prop('checked');
$('#isSelected').prop('checked', !isChecked);
$('#isSelected').trigger('change');
});
Also Read : How to get radio input value in jQuery ?