To check if a checkbox is checked or not you can use the checked
attribute of the checkbox element. The value of the checked
attribute can either be true or false based on the current state of the checkbox.
If the checkbox is checked, the value of the checked attribute is set to true otherwise it is set to false. We can take advantage of this concept and easily get the current state of the checkbox.
See the following working example:
Example:
var checkbox = document.getElementById('myCheckbox'); var result = document.getElementById('result'); function checkValue(){ if(checkbox.checked){ result.innerText = 'checked'; }else{ result.innerText = 'unchecked'; } }
If you are using the addEventListener()
method on the checkbox then you can check the current state of the checkbox using event.target.checked
.
If the value of the event.target.checked
is true then the checkbox is checked otherwise it is unchecked.
See the following working example:
Example:
var checkbox = document.getElementById('myCheckbox'); var result = document.getElementById('result'); checkbox.addEventListener('change',function(event){ if(event.target.checked){ result.innerText = 'checked'; }else{ result.innerText = 'unchecked'; } });