How can a checkbox be checked/unchecked using JavaScript, jQuery or vanilla?
I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.
So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.
Try This:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
We can checked a particulate checkbox as,
$('id of the checkbox')[0].checked = true
and uncheck by ,
$('id of the checkbox')[0].checked = false
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
Important behaviour that has not yet been mentioned:
Programmatically setting the checked attribute, does not fire the change
event of the checkbox.
See for yourself in this fiddle:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11)
Some day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click()
method of the checkbox element, like this:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to true
or false
. Remember that the change
event should only fire, when the checked attribute actually changes.
It also applies to the jQuery way: setting the attribute using prop
or attr
, does not fire the change
event.
checked
to a specific valueYou could test the checked
attribute, before calling the click()
method. Example:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click