Sometimes, we want to change or get check state of checkbox with JavaScript.
In this article, we’ll look at how to change or get check state of checkbox with JavaScript.
How to change or get check state of checkbox with JavaScript?
To change or get check state of checkbox with JavaScript, we can use the checked
property.
For instance, we write
<input type="checkbox" id="cbxTodos" name="cbxTodos" />
to add a checkbox.
Then we write
const elCheckBox = document.getElementById("cbxTodos");
elCheckBox.onchange = () => {
console.log(elCheckBox.checked);
};
to select the checkbox with getElementById
.
Then we set its onchange
property to a function that’s called when the checkbox changes value.
In it, we get the checked value with the checked
property.
checked
can also be set to change the checked state.
Conclusion
To change or get check state of checkbox with JavaScript, we can use the checked
property.