mercredi 18 octobre 2017

Canceling checkbox's click event prevents checking it?

I need to have a list of checkboxes with the condition that at least one of them must be checked.
The following code produces that effect.

document.querySelector('div').addEventListener('click', function(evt) {
  if (this.querySelectorAll('input:checked').length == 0)
    evt.preventDefault();
});
<div>
  <input type=checkbox checked>
  <input type=checkbox>
  <input type=checkbox>
</div>

That's fine, however, I don't understand why this code even works.

Firstly, I'm doing a .preventDefault() on the click event only after I've checked the condition that says there are no checkboxes checked. So canceling the click event at this point should make no difference.

Secondly, the code works even if you try to check the checkboxes using the keyboard, which is totally weird because I'm only canceling the click event.

Please explain why the code works the way it does.




Aucun commentaire:

Enregistrer un commentaire