Javascript 使用javascript从单选按钮获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8233308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the value from a radio button using javascript
提问by Joseph Robins
I have a HTML form with radio inputs and want to use javascript to analyse the results. I am getting stuck at retrieving the form information in my JavaScript function:
我有一个带有无线电输入的 HTML 表单,想使用 javascript 来分析结果。我被困在我的 JavaScript 函数中检索表单信息:
function getResults(formInput){
alert (formInput.question1);
}
Where question1 is the "name" of my radio button group.
其中 question1 是我的单选按钮组的“名称”。
This returns "object Nodelist" and I haven't a clue what's wrong, I would expect it to return "1", which is the value of my radio button when selected.
这将返回“对象节点列表”,我不知道出了什么问题,我希望它返回“1”,这是我选择的单选按钮的值。
I don't want to work out which radio button is selected and which isn't, I need to know the value associated with the selected radio button.
我不想确定哪个单选按钮被选中,哪个没有,我需要知道与所选单选按钮关联的值。
回答by James Hill
The object Nodelistthat you're referring to is being returned because you have a group of elements that share the same name. If you want to see the value of the radio button that's checked, you need to loop through the collection:
在object Nodelist那你指的是被退回,因为你有一组共享相同名称的元素。如果要查看选中的单选按钮的值,则需要遍历集合:
function getResults() {
var radios = document.getElementsByName("question1");
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
break;
}
}
}
Here's a working jsFiddle.
回答by bergman
you can get a more simple and elegant solution:
你可以得到一个更简单优雅的解决方案:
<input type=radio name=my_radio value=value_1>
var my_form = document.querySelector('#my_form');
var my_radio = my_form.elements.my_radio;
alert(my_radio.value) // this is the radionodelist.value you can check it on mdn

