How to change or get the check state of the checkbox with JavaScript?

Estimated read time 1 min read

You can change the check state of a checkbox in JavaScript by using the checked property. To retrieve the state of the checkbox, you can read the checked property, and to set the state, you can assign a boolean value to the checked property.

Here’s an example of how you can toggle the check state of a checkbox:

const checkbox = document.querySelector('input[type="checkbox"]');

checkbox.addEventListener('click', function() {
  this.checked = !this.checked;
});

And here’s an example of how you can retrieve the state of a checkbox:

const checkbox = document.querySelector('input[type="checkbox"]');

console.log(checkbox.checked);

In the first example, we attach a click event listener to the checkbox and toggle its checked property, so every time the checkbox is clicked, its state will be changed. In the second example, we simply retrieve the current state of the checkbox and log it to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply