Javascript / HTML复选框获得选中的值 [英] Javascript/HTML Checkboxes get checked value

查看:171
本文介绍了Javascript / HTML复选框获得选中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个复选框,每个组只有一个可选组件。下面是复选框的示例:

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>

我有一个javascript函数,通过传递单选按钮组),是否有一个等价的人可以帮助我以类似的方式获得复选框的值(每个组中只有一个)?

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?

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;
            }
        }
    }

p>

推荐答案

实际上,如果你更正了 SingleSelect 或您的标记;您的标记使用 question1options 等名称,但您对 SingleSelect 的调用使用了 question1option (结尾没有 s )。修复此问题并执行操作:实例

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

显然,当你点击它们时,复选框不会自动取消选择其他具有相同名称的复选框(这是 type =radio)。但我假设你知道。 : - )

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. :-)

这篇关于Javascript / HTML复选框获得选中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆