Reputation:
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
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
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