Check Uncheck Checkbox on Button Click JavaScript

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.

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.

How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color JavaScript Change li Text JavaScript Remove id from Element Check If id Exists in JavaScript How To Delete Table Row by id in JavaScript Update Textarea value in JavaScript Change Variable Value in JavaScript Uncheck Radio Button Dynamically JavaScript Check Radio Button Dynamically JavaScript JavaScript Check if Radio Button is Checked or Not Change h1 Tag Text with JavaScript