0

I want to select a family of radio box elements of the name "clientName." I can do so using:

var x = document.getElementsByName("gender");

I want to create an event listener, such that if any of the radio buttons are clicked, it logs to the console the ID of the clicked element. I imagine this involves using "this" and an onclick event. So I tried the following, and it does not work:

x.addEventListener("click", myScript);
x.onclick=function(){console.log(this)};

However, this does not seem to do anything. How would I achieve the desired result most elegantly?

[[EDIT: This is clearly not a duplicate of that post. This post does not have the jquery tag selected. I am not interested in Jquery answers.]]

COMisHARD
  • 867
  • 3
  • 13
  • 36
  • Hint: `.addEventListener()` and `.onclick` both apply to individual DOM elements, but `.getElementsByName()` returns a *list*... – nnnnnn Aug 13 '16 at 04:34
  • I don't believe that .getElementsByName returns a list. I believe it returns an object. – COMisHARD Aug 13 '16 at 04:35
  • 1
    *"I believe it returns an object"* - And that object is definitely a list, even if only one element has the specified name. It's getElement**s**ByName - note the "s". – nnnnnn Aug 13 '16 at 04:37
  • 2
    Check the second code snippet of the accepted answer. It doesn't use jQuery. You just need to replace the handler body with `console.log(this.id)`. – Ram Aug 13 '16 at 04:40

0 Answers0