vendredi 15 janvier 2021

Why does preventDefault on parent element disable programtically checking child checkbox?

A div element's click event has e.preventDefault() at the beginning. That makes manually clicking the checkbox input or it's associated label inside no longer works.

With the help of some more JavaScript code, manually clicking the label works. However, the checkbox input just does not work despite the fact that similar JavaScript code has been implemented for it. Why?

document.querySelector('div').onclick = function (e)
{
      e.preventDefault();
      if (e.target.tagName.toUpperCase() == 'LABEL')
      {
          e.target.previousElementSibling.checked = !e.target.previousElementSibling.checked;
      }
      else if (e.target.tagName.toUpperCase() == 'INPUT')
      {
          e.target.checked = !e.target.checked;
      }
}
<div>
      <input  id="check" type="checkbox">
      <label for="check">Label Text</label>
</div>



Aucun commentaire:

Enregistrer un commentaire