How to stop label from toggling the input checkbox with JavaScript?

Sometimes, we want to stop label from toggling the input checkbox with JavaScript.

In this article, we’ll look at how to stop label from toggling the input checkbox with JavaScript.

How to stop label from toggling the input checkbox with JavaScript?

To stop label from toggling the input checkbox with JavaScript, we can call preventDefault in the label’s click handler.

For instance, we write:

<label for="checked">checked</label>
<input type="checkbox" id="checked" name="checked">

to add a label and an input.

Then we write:

const label = document.querySelector('label')
label.onclick = (e) => {
  e.preventDefault()
}

to select the label with querySelector.

Then we set label.onclick to a function that calls e.preventDefault to stop the label from toggling the checkbox.

Conclusion

To stop label from toggling the input checkbox with JavaScript, we can call preventDefault in the label’s click handler.