user14638116
user14638116

Reputation:

Radio button is checked on click event even though preventDefault is ran

thing.addEventListener('click', click)

function click(e) {
    e.preventDefault()
    console.log(e.target.checked);
}
  <input id="thing" type="radio" name="gender">

Why is e.target.checked == true even though preventDefault is ran and the radio button is not checked?

Upvotes: 1

Views: 156

Answers (2)

jacobkim
jacobkim

Reputation: 1090

Because preventDefault() removed value from the tag which an event function is fired. But when after preventDefault() is fired e.target.checked is false as below. So finally e.target.checked is false.

thing.addEventListener('click', click)

function click(e) {
    e.preventDefault()
    console.log(e.target.checked);
    setTimeout(()=> console.log(e.target.checked), 100);
}
<input id="thing" type="radio" name="gender">

Upvotes: 0

Liftoff
Liftoff

Reputation: 25392

By the time you call preventDefault, the radio button is already checked. PreventDefault simply undoes this. You can see this if you set a short timeout on the console log.

thing.addEventListener('click', click)

function click(e) {
    e.preventDefault();
    setTimeout(function(){
      console.log(e.target.checked);
    }, 10);
}
<input id="thing" type="radio" name="gender">

Upvotes: 1

Related Questions