Change Check State of Checkbox with JavaScript

12/31/2021

Contents

In this article, you will learn how to change check state of checkbox with JavaScript.

Get check state of checkbox

The checked state of the input element can be obtained with the checked property of HTMLInputElement.

The checked property returns true if the target element has checked, false otherwise.

inputElement.checked

Below is the sample code.
Check the return value of the checked property in the two checkboxes.

HTML

<label><input type="checkbox" name="item[]" value="1">Item 1</label>
<label><input type="checkbox" name="item[]" value="2" checked>Item 2</label >

JavaScript

const cb1 = document.querySelectorAll('input')[0];
const cb2 = document.querySelectorAll('input')[1];

console.log('cb1:' + cb1.checked);
console.log('cb2:' + cb2.checked);

Change check state of checkbox

You can change the check state by overriding the value of the checked property.

Below is the sample code.

HTML

<label><input type="checkbox" name="item[]" value="1">Item 1</label>

JavaScript

const cb = document.querySelector('input');
cb.checked = true;