Pippi
Pippi

Reputation: 2571

How do I record value of a set of radio buttons with the same name but different id?

I have a set of radio buttons, and only one can be selected, and its value recorded. I ran the code below in this link, but got undefined error:

<!DOCTYPE html>
<html>
<body>

<td class="tg-031e"><input type="radio" name="ribbon_1" id="ribbon_1_1" value="1" size="15" />1</td>
<td class="tg-031e"><input type="radio" name="ribbon_1" id="ribbon_1_2" value="5" size="15" />2</td>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementsByName('ribbon_1').value;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

How can I get the correct value?

Upvotes: 0

Views: 599

Answers (2)

Sam1604
Sam1604

Reputation: 1489

The following script checks all the radio buttons with the name "ribbon_1" individually. But your script "getElementsByName("ribbon_1")" returns collection of radio buttons. So it returns Undefined.

 function myFunction() {
            var inputs = document.getElementsByName("ribbon_1");
            for (var i = 0; i < inputs.length; i++) {
              if (inputs[i].checked) {
                 document.getElementById("demo").innerHTML =inputs[i].value;
              }
            }

Try this.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

getElementsByName() as the name suggestes returns an array of elements, so you will have to iterate through them and find out which one is checked

function myFunction() {
    var els = document.getElementsByName('ribbon_1');
    for (var i = 0; i < els.length; i++) {
        if (els[i].checked) {
            document.getElementById("demo").innerHTML = els[i].value;
        }
    }
}
<table>
  <tr>
    <td class="tg-031e"><input type="radio" name="ribbon_1" id="ribbon_1_1" value="1" size="15" />1</td>
    <td class="tg-031e"><input type="radio" name="ribbon_1" id="ribbon_1_2" value="5" size="15" />2</td>
  </tr>
</table>
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

Upvotes: 2

Related Questions