How to Check if Checkbox is Checked in Javascript

Advertisement

You can check if checkbox is checked or not in Javascript by using the checked property of the checkbox.

Check if checkbox checked Javascript

Start by creating a checkbox element in HTML.

<label for="legal-terms">
  <input type="checkbox" id="legal-terms" />
  I agree with the terms and conditions
</label>

In Javascript you can check the state of the checkbox using: document.querySelector('#legal-terms').checked or document.querySelector('#legal-terms:checked') !== null

The checked property is a boolean that is either true or false.

Example 1

document.querySelector('#legal-terms').addEventListener('click', (event) =>{
  if(event.target.checked){
    console.log("The checkbox has been checked");
  }  
})

Result

Checked and unchecked checkbox Javascript

If you check the browser console, you will see that the checkbox fires only when the checkbox is checked.

Example 2

document.getElementById('legal-terms').addEventListener('click', (event) =>{
  if(event.target.checked){
    console.log(event.target.checked)
  } else{
    console.log(event.target.checked)
  }
})

Result

If checkbox is checked, the checkbox checked value is true. When checkbox is unchecked, the checked value turns to false.

author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.