Javascript/HTML Checkboxes get checked value

2019-08-12 14:18发布

问题:

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?

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.

回答1:

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

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