How to check whether a checkbox input element is checked using JavaScript?

January 23, 2021 - 2 min read

To check whether the checkbox input element is checked, you can use the checked property of the checkbox element in JavaScript.

TL;DR

// get reference to the checkbox input element
const checkbox = document.getElementById("myCheckbox");

// check if checkbox checked
console.log(checkbox.checked);

For an example, consider we have a checkbox input like this,

<!-- Checkbox input -->
<input type="checkbox" id="myCheckbox" />

The first thing we have to do is get the reference to the checkbox input element. We can use the document.getElementById() or similar functions and pass the id of the checkbox element to the function to get the reference to it.

It can be done like this,

// get refernce to the checkbox input element
const checkbox = document.getElementById("myCheckbox");

After that, we can add a click event to the checkbox element using the addEventListener() method on the element so that when the user clicks on it, we can get the properties regarding it.

// get refernce to the checkbox input element
const checkbox = document.getElementById("myCheckbox");

// add click even to checkbox
checkbox.addEventListener("click", (event) => {});

Now, all we have to do is use the checked property in the element which will give us the state of the checkbox.

It can be don elike this,

// get refernce to the checkbox input element
const checkbox = document.getElementById("myCheckbox");

// add click event to checkbox
checkbox.addEventListener("click", (event) => {
  console.log(event.target.checked);
});

See this example live in JSBin.

That's it.

Feel free to share if you found this useful 😃.