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.

Change font-size using JavaScript Get Font Size of any Tag using JavaScript Change Position of HTML Element using JavaScript How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom 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