In this tutorial we will see how to Check Uncheck Checkbox on Button Click with JavaScript. HTML DOM Input Checkbox checked Property can be used to change the state of checkbox and to check and uncheck it using the button tag.
Table of Contents
JavaScript checked Property
The JavaScript checked Property is used to set the state of checkbox or to read it's state to see whether it is already checked or not.
In this example we will use the checked property to check and uncheck the checkbox on click of a button.
HTML Code
HTML Code is given below, in this code we have a checkbox type input element and label tag.
A button tag is used with onclick event to execute a JavaScript function.
<label>Checkbox</label>
<input id='checkbox' type="checkbox">
<br><br>
<button onclick='checkUncheck()'>Check/Uncheck</button>
JavaScript Code
JavaScript Code is given below, in this code checked property is first used to check the current state of checkbox.
If statement is used for this purpose. If the checkbox is already checked then checkbox is unchecked using checked property otherwise the checkbox is checked.
getElementById() method is used to select the checkbox.
<script>
function checkUncheck()
{
var checkbox = document.getElementById('checkbox');
if(checkbox.checked)
{
checkbox.checked = false;
}
else
{
checkbox.checked = true;
}
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Check Uncheck Checkbox on Button Click using JavaScript.