简体   繁体   English

通过表单ID访问单选按钮值

[英]access radio button value through form id

I am working on a website with several forms of radio buttons, one of which is like this: 我正在一个有几种形式的单选按钮的网站上工作,其中一个是这样的:

<form id = "configuration">
    <ul>
        <li><input type="radio" name="configuration" id="0" value="0"/> GT Manual</li>
        <li><input type="radio" name="configuration" id="1" value="1"/> GT Automatic</li>
    </ul>
</form>

IS THERE a way (javascript) that I can access the value of the radio buttons directly, eg 是有一种方法(javascript),我可以直接访问单选按钮的值,例如

var value = document.getElementById("configuration").configuration.value;

(here the first "configuration" is the form id while the second 'configuration' is the name, rather than looping through each element in the form to check which button is selected? (这里第一个“配置”是表单ID,而第二个“配置”是名称,而不是循环遍历表单中的每个元素以检查选择了哪个按钮?

Thank you! 谢谢!

Get it like this... 得到这样的......

var radios = document.getElementsByName('configuration');
 for (i = 0; i < radios.length; i++) {
    if (radios[i].type == 'radio' && radios[i].checked) {
        alert(radios[i].value);
    }
}

No. You have to loop over the radio group to find out which one is selected. 不可以。您必须遍历无线电组以找出选择了哪一个。 .configuration is a standard NodeList, not a 'subclass' with extra features for handling radio groups. .configuration是一个标准的NodeList,而不是具有处理无线电组的额外功能的“子类”。

Since the Radio buttons are part of a group they have the same name are are identified by a distinct ID. 由于单选按钮是组的一部分,因此它们具有相同的名称由不同的ID标识。 The answer provided by KyleK is perfectly valid. KyleK提供的答案完全有效。 However here is another way to do it http://jsfiddle.net/9W76C/ 然而,这是另一种方法来做到这一点http://jsfiddle.net/9W76C/

if (document.getElementById('0').checked) {
   alert("GT Manual");
}

I would also suggest you use jquery... 我也建议你使用jquery ...

If you're using jQuery, you can do $('#configuration input:checkbox').val(); 如果你正在使用jQuery,你可以做$('#configuration input:checkbox').val(); to know which one is selected 知道选择哪一个

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

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