Sometimes, we want to attach event listener to a radio button with JavaScript.
In this article, we’ll look at how to attach event listener to a radio button with JavaScript.
How to attach event listener to a radio button with JavaScript?
To attach event listener to a radio button with JavaScript, we can loop through each radio button and set its onclick
property.
For instance, we write:
<form>
<input type="radio" name="myradio" value="A" />
<input type="radio" name="myradio" value="B" />
<input type="radio" name="myradio" value="C" />
<input type="radio" name="myradio" value="D" />
</form>
to add a form with radio buttons.
Then we write:
const radios = document.querySelectorAll('input')
for (const radio of radios) {
radio.onclick = (e) => {
console.log(e.target.value);
}
}
to select the radio buttons with querySelectorAll
.
Then we loop through them with a for-of loop.
In it, we set radio.onclick
to a function that logs the value
attribute of the radio button.
Conclusion
To attach event listener to a radio button with JavaScript, we can loop through each radio button and set its onclick
property.