How to Check if Checkbox is Checked in Javascript
You can check if checkbox is checked or not in Javascript by using the checked
property of the checkbox.
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
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
.