To set a checkbox as checked using JavaScript, the simplest way is to target the input element and change its checked property to true.
document.getElementById("checkboxInput").checked = true;
If we want to uncheck a checkbox using JavaScript, we can target the input element and change its checked property to false:
document.getElementById("checkboxInput").checked = false;
Let’s say we have the following HTML:
To set the first checkbox as checked, we can use the getElementById() method to target its checked property:
document.getElementById("checkbox-1").checked = true;
Note we can also set a checkbox as checked easily using jQuery.
How to Set a Checkbox as Checked on Click with JavaScript
We can check a checkbox using JavaScript very easily by combining the checked property with a click event.
Let’s say we have the following HTML code and we want to set the checked value of our checkbox as checked in the HTML below:
Check Checkbox
We can utilize an onclick event and getElementById() method to set the checked property of the checkbox.
Below is the JavaScript code which will allow us to set our checkbox as checked.
function setChecked(){
document.getElementById('checkbox-1').checked = true;
};
The final code and output for this example of how to check a checkbox on click using JavaScript is below:
Code Output:
Full Code:
Check Checkbox
How to Uncheck a Checkbox Using JavaScript
Just as easily as we can check a checkbox, we can also uncheck a checkbox using JavaScript.
Let’s say we have the following HTML code and we want to set the checked value of our checkbox as unchecked in the HTML below:
Uncheck Checkbox
We can once again utilize an onclick event and getElementById() method to set the checked property of the checkbox to false.
Below is the JavaScript code which will allow us to set our checkbox as unchecked.
function setUnchecked(){
document.getElementById('checkbox-1-1').checked = false;
};
The final code and output for this example of how to uncheck a checkbox on click using JavaScript is below:
Code Output:
Full Code:
Uncheck Checkbox
Hopefully this article has been useful for you to understand how to check a checkbox and uncheck a checkbox using JavaScript.