Categories
JavaScript Answers

How to attach event listener to a radio button with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to attach event listener to a radio button with JavaScript?”

Your example was very useful but I need something more complicated. I need to attach different event listener to radio buttons with switch statement but I cant reach any button, like this:
switch (event.target.value) {
case ‘new-movies’:
checking();
break;
I get an error:
properties of undefined (reading ‘target’)

Leave a Reply

Your email address will not be published. Required fields are marked *