[Solved] Why does the e.preventDefault function in javascript not work for the checkbox? [closed]


You have an spelling-error in your code: querySelecotr should be querySelector.
You can also use getElementById to get an element by its id-property.

Both versions work in the browsers i tested (Firefox, Chrome, Safari).

If you use preventDefault(), the checked-state will be restored after the event-handler is completed. So any change inside that event-handler will be reverted. A workaround would be to toggle the state with inside an setTimeout-call (see checkbox3-example below).

let idCheckbox = document.getElementById("checkbox");
idCheckbox.addEventListener("click", function(e) {
  e.preventDefault();
});


let idCheckbox2 = document.querySelector("#checkbox2");
idCheckbox2.addEventListener("click", function (e) {
  e.preventDefault();
});

let idCheckbox3 = document.querySelector("#checkbox3");
idCheckbox3.addEventListener("click", function (e) {
  e.preventDefault();
  setTimeout(() => {
    if (idCheckbox3.checked == false) {
      idCheckbox3.checked = true;
    } else {
      idCheckbox3.checked = false;
    }
  }, 50);
});
<input id="checkbox" name="checkbox" type="checkbox"/>
<label class="sub-label" for="checkbox">Accept checkbox 1</label>
<br>
<input id="checkbox2" name="checkbox2" type="checkbox"/>
<label class="sub-label" for="checkbox2">Accept checkbox 2</label>
<br>
<input id="checkbox3" name="checkbox3" type="checkbox"/>
<label class="sub-label" for="checkbox3">Accept checkbox 3</label>
<br>

14

solved Why does the e.preventDefault function in javascript not work for the checkbox? [closed]