How to check if a checkbox is checked using JavaScript?

By

Learn how to check whether a checkbox is checked in JavaScript by inspecting its checked property, and why you should not rely on getAttribute or value.

~~~

Inspect the checked property of the element. It’s true when the checkbox is ticked, false when it’s not.

Say you have this checkbox:

<input type="checkbox" class="checkbox" />

You can see if it’s checked using

document.querySelector('.checkbox').checked

You can also check if looking for .checkbox:checked does not return null:

document.querySelector('.checkbox:checked') !== null

but I think looking for .checked is cleaner.

How to react when the checkbox changes

Most of the time you don’t want to poll the checkbox. You want to run code the moment the user toggles it.

Listen for the change event, and read checked inside the handler:

const checkbox = document.querySelector('.checkbox')

checkbox.addEventListener('change', (event) => {
  if (event.target.checked) {
    console.log('checked')
  } else {
    console.log('not checked')
  }
})

The change event fires on clicks and also when the user toggles the checkbox with the keyboard, so you cover both cases with one listener.

The attribute and the property are two different things

This is where people get confused.

The checked attribute in the HTML only sets the initial state of the checkbox:

<input type="checkbox" checked />

After the page loads, the attribute never changes. The user can click the checkbox on and off all day, and getAttribute('checked') keeps returning the same thing.

The checked property, instead, always reflects the current state. That’s why you read the property, not the attribute.

Do NOT use getAttribute() looking for the checked attribute value, because that’s always there if the checkbox is checked by default in the HTML, even after the user unchecks it.

If you ever need the initial state in JavaScript, that’s what the defaultChecked property is for.

Don’t check the value either

Also don’t check for the value of a checkbox element. It’s on by default, regardless whether the checkbox is checked or not:

document.querySelector('.checkbox').value // 'on'

The value only tells you what gets submitted with a form when the checkbox is checked. It says nothing about whether it currently is.

~~~

Related posts about platform: