I'm trying to log the checked
property of a radio element on click
event. But It returns the wrong value.
const radio = document.querySelector('input[type=radio]')
radio.addEventListener('click', (ev) => {
ev.preventDefault();
console.log(ev.target.checked);
})
<p class="rInput">
<input type="radio" name="R" id="ID">
<label for="ID">The label</label>
</p>
When clicking on the radio it should log the checked status but it always logs true
.
My solution to this was adding a timeOut
of 0 millisecond, and it worked
const radio = document.querySelector('input[type=radio]')
radio.addEventListener('click', (ev) => {
ev.preventDefault();
setTimeout(() => {
console.log(ev.target.checked);
}, 0);
})
<p class="rInput">
<input type="radio" id="ID">
<label for="ID">The label</label>
</p>
But what is the problem and why this happens? Is there a better solution?