javascript - 如何获得已检查 radio 的值(value)

标签 javascript radio-button getelementsbyname

我正在尝试使用以下代码获取选中的单选按钮的值:

<html>
<head>
<script type="text/javascript" >
    window.onload = initAll;

    function initAll(){     
        var allAnchors = document.getElementsByName("options");
        for ( var int = 0; int < allAnchors.length; int++) {
            if(allAnchors[int].className == "buttonLink"){
                allAnchors[int].onclick = fetchQuestion;
            }
        }
    }

    function fetchQuestion(){

        var toLoad = this.href;
        var selectedAnswer = "";                
        var allRadio = document.getElementsByTagName("input");

        for(var i = 0;i<allRadio.length; i++){
            if(allRadio[i].checked == true){
                selectedAnswer = allRadio[i].value;
            }
        }       
            alert(selectedAnswer);
                return false;
         }
</script>
</head>
<body>
<input type="radio" name="options" value="optA" />&nbsp; &nbsp;Operating System is used for Efficeint Resource Sharing Operating System is used for Efficeint Resource Sharing Operating System is used for Efficeint Resource Sharing <br/>
             <input type="radio" name="options" value="optB" />&nbsp; &nbsp;Operating System is used for Efficeint Resource Sharing <br/>
             <input type="radio" name="options" value="optC" />&nbsp; &nbsp;Operating System is used for Efficeint Resource Sharing <br/>
             <input type="radio" name="options" value="optD" />&nbsp; &nbsp;Operating System is used for Efficeint Resource Sharing <br/>
<a href="SubmitSheet" class="buttonLink">Submit</a>
        <a href="NextQuestion" class="buttonLink">Next</a>
        <a href="PreviousQuestion" class="buttonLink">Previous</a>
        <a href="PassQuestion" class="buttonLink">Pass</a>
</body>
</html>

在这里,如果我使用了 document.getElementByTagName("input"),那么它就可以工作了。但对于 document.getElementByName("options") 则不是。所以这有什么问题??我不能将 document.getElementByName 与单选按钮一起使用吗?

最佳答案

也许你的意思是document.getElementsByName() .请注意复数形式,因为它可能返回多个节点。

关于javascript - 如何获得已检查 radio 的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5733547/

相关文章:

javascript - 用于更改图像的单选按钮(Javascript/HTML)

javascript - For循环数组设置元素等于一个变量

javascript - 我怎样才能只选择一个单选按钮?

html - 单选按钮在 IE7 和 IE9 中未对齐

javascript - 将项目从 JSON 数组添加到列表

javascript - 使用 javascript 在 github 页面上写入文件

javascript - 选择 allElementsByID 并向其添加类时出错

javascript - 如何获取名称在 Javascript 中已知的元素的 ID

javascript - cookies 。使用 javascript 在 cookie 中附加许多值

javascript - 流量: turn off "Unused suppression" error for supress_comment