Javascript/HTML 复选框获得选中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13858200/
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
Javascript/HTML Checkboxes get checked value
提问by user1149620
I have several checkboxes, each group with only one selectable component. An example of the checkboxes is below:
我有几个复选框,每组只有一个可选组件。复选框的示例如下:
<label class="checkbox inline">
<input type="checkbox" id="question1option1" name="question1options" value="correct" onclick="SingleSelect('question1option',this)"> 1
</label>
<label class="checkbox inline">
<input type="checkbox" id="question1option2" name="question1options" value="wrong" onclick="SingleSelect('question1option',this)"> 2
</label>
<label class="checkbox inline">
<input type="checkbox" id="question1option3" name="question1options" value="wrong" onclick="SingleSelect('question1option',this)"> 3
</label>
<label class="checkbox inline">
<input type="checkbox" id="question2option1" name="question2options" value="correct" onclick="SingleSelect('question2option',this)"> 1
</label>
<label class="checkbox inline">
<input type="checkbox" id="question2option2" name="question2options" value="wrong" onclick="SingleSelect('question2option',this)"> 2
</label>
<label class="checkbox inline">
<input type="checkbox" id="question2option3" name="question2options" value="wrong" onclick="SingleSelect('question2option',this)"> 3
</label>
I have a javascript function that pulls out which radio button is selected by passing the radio button group (below), is there an equivalent someone can help me with to get the value of the checked checkbox (only one in each 'group') in a similar way please?
我有一个 javascript 函数,它通过传递单选按钮组(下面)来拉出选择的单选按钮,是否有等效的人可以帮助我获取选中复选框的值(每个“组”中只有一个)类似的方式好吗?
function getRadioValue (theRadioGroup)
{
for (var i = 0; i < document.getElementsByName(theRadioGroup).length; i++)
{
if (document.getElementsByName(theRadioGroup)[i].checked)
{
return document.getElementsByName(theRadioGroup)[i].value;
}
}
}
Thanks in advance.
提前致谢。
采纳答案by T.J. Crowder
Actually, that same function will work if you correct your calls to SingleSelect
or your markup; your markup is using names like question1options
but your calls to SingleSelect
are using names like question1option
(without the s
at the end). Fix that and it works: Live Example
实际上,如果您更正您的调用SingleSelect
或标记,同样的功能将起作用;您的标记使用了类似的名称,question1options
但您的调用SingleSelect
使用了类似的名称question1option
(s
末尾没有)。修复它并且它有效:Live Example
Obviously, though, checkboxes don't automatically de-select other checkboxes with the same name when you click them (that's what type="radio"
is for). But I assume you know that. :-)
但是,很明显,当您单击复选框时,复选框不会自动取消选择具有相同名称的其他复选框(这就是type="radio"
目的)。但我假设你知道这一点。:-)