In JavaScript, is there an event triggered when a radio button is checked?
<input type="radio" name="radio" id="radio1">
<input type="radio" name="radio" id="radio2" checked>
<input type="radio" name="radio" id="radio3">
Is something like the following possible?
document.getElementById("radio1").addEventListener('checked', () => {
// Do something when the first radio button is checked
})
JSfidde: https://jsfiddle.net/Imabot/ko486uqe/2/
PLEASE read before answering or marking as duplicate. My question is not "How to run JS code when the radio button is checked". My question is "Is there an event triggered only when the radio button is checked", this is not exactly the same thing…
2
Answers
Try this:
There’s no such special event for radio buttons only.
There’s not such special event for
"radioChecked"
.To test the checked state you need to do it on your own.
The best would be to use event delegation, check if the element target is a Radio Element, and then go for its
cehecked
property:Whilst using
Event.target.closest()
is always a good practice, you can also use theElement.matches()
method when handling actionElements likeinput
: