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?
Ok so this is a bit of a weird question. Let me go try to explain why I call it a weird question:
console.log(rI.checked); therefore you will always log TRUE.I hope that makes sense. As a follow up, I think you should CHECK out (pun intended) how to make a button unchecked. This here is a great answer on how to do it using JS without any frameworks.
UPDATED Code Snippet:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($(this).prop("checked") === true){
console.log("Checkbox is checked.");
}
else if($(this).prop("checked") === false){
console.log("Checkbox is unchecked.");
}
});
});
It would be simpler to just disable the radio button you don't want clicked.
const radios = document.querySelectorAll('input[type="radio"]');
radios.forEach(radio => radio.addEventListener('click', handleClick, false));
function handleClick(e) {
const { id, checked } = e.target;
console.log(id, checked);
};
<div>
<label for="1">First
<input name="radio" id="1" type="radio">
</label>
<label for="2">Second (disabled)
<input name="radio" id="2" type="radio" disabled>
</label>
<label for="3">Last
<input name="radio" id="3" type="radio">
</label>
</div>