理解选中的单选按钮有问题

时间:2017-10-06 21:40:58

标签: javascript html

我试图通过JavaScript验证我的表单,而不是手动检查每个单选按钮,我决定循环通过一组单选按钮,检查它们是否被检查。

我只是想看看是否检查了一组单选按钮。但我面临的问题是。当我检查其中任何一个时,它返回true和false。如果我不检查,它们都会返回false,但如果我检查一个,则返回true和false。

这是我的代码:



<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
	<fieldset id="group1">
		<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
		<input type="radio" name="yesnocheck" value="No"><span>No</span>
	</fieldset>
    <input type="submit" value="Send">
</form>
&#13;
{{1}}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

试试这个:

function getRadioValue(name) {

    let elements = document.getElementsByName(name);
    for (let i = 0; i < elements.length; i++) {
        if (elements[i].checked) {
            return elements[i].value;
        }
    }

    return null;

}

function validateForm() {

    var yesnocheck = getRadioValue("yesnocheck");
    console.log(yesnocheck);

    return false;

}

如果未选中任何内容,则getRadioValue函数将返回null。 如果选中任何选项,它将返回它的值。

答案 1 :(得分:0)

尝试使用document.forms[0].yesnocheck

function validateForm()
{
    return (document.forms[0].yesnocheck.value.length  > 0 &&
            document.forms[0].yesnoremote.value.length > 0 &&
            document.forms[0].yesnocable.value.length  > 0 &&
            document.forms[0].condition.value.length   > 0);
}
<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
	<fieldset id="group1">
		<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
		<input type="radio" name="yesnocheck" value="No"><span>No</span>
	</fieldset>
		<label for="gateremote">Gate remote batteries checked?:</label>
		<input type="radio" name="yesnoremote" value="Yes"><span>Yes</span>
		<input type="radio" name="yesnoremote" value="No"><span>No</span>

		<label for="internetcabletv">Internet and Cable TV checked?:</label>
		<input type="radio" name="yesnocable" value="Yes"><span>Yes</span>
		<input type="radio" name="yesnocable" value="No"><span>No</span>

		<label for="unitcondition">Unit Condition?:</label>
		<input type="radio" name="condition" value="clean"><span>Clean</span>
		<input type="radio" name="condition" value="light"><span>Light</span>
		<input type="radio" name="condition" value="heavy"><span>Heavy</span>
		<input type="radio" name="condition" value="superheavy"><span>SuperHeavy</span>
    
    <input type="submit" value="Send">
</form>