简体   繁体   English

如何记录一组名称相同但ID不同的单选按钮的值?

[英]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: 我在此链接中运行了以下代码,但收到undefined错误:

<!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 顾名思义, getElementsByName()返回一个元素数组,因此您将不得不遍历它们并找出要检查的元素

 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. 以下脚本分别检查名称为“ ribbon_1”的所有单选按钮。 But your script "getElementsByName("ribbon_1")" returns collection of radio buttons. 但是您的脚本“ getElementsByName(” ribbon_1“)”返回单选按钮的集合。 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 . 试试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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