Using JavaScript or jQuery Check/Uncheck checkbox
Here are a few ways to checked or unchecked a checkbox using javascript or jquery.
Using checked
We can get and modify the checked state through document.getElementById("checkbox").checked
. It should be the easiest way.
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jquery prop method
prop method works with jquery 1.6 and above.
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jquery attr method
attr method works with jquery 1.5 and below.
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
click event
We know that if the checkbox is checked or unchecked in the browser, the click event will be triggered. So we can toggle the checked state with the click event.
document.getElementById('checkbox').click();
// or use jquery
$('#checkbox').click();