简体   繁体   中英

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?

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> 

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM