如何验证单选按钮?

时间:2014-02-07 09:39:57

标签: javascript html

我正在尝试验证一组在提交时输出消息的单选按钮,通知用户他们必须在继续之前进行选择。下面的代码永远不会识别按钮被选中并始终输出警报消息。我将如何调整此代码以使其正常工作?

单选按钮:

<input type="radio" name="examtype" value="GCSE"onclick="return confirmation();"/>GCSE

<input type="radio" name="examtype" value="AS" onclick="return confirmation();"/> AS

<input type="radio" name="examtype" value="A2" onclick="return confirmation();"/> A2 </td> </tr>

确认onclick的功能:

function confirmation() {

    for (var i=0; i < document.ExamEntry.examtype.length; i++)
       {
       if (document.ExamEntry.examtype[i].checked)
          {
            var answer = confirm(document.ExamEntry.examtype[i].value)

        if (answer){
            document.ExamEntry.examtype[i].checked = true;

        }
        else{
            document.ExamEntry.examtype[i].checked = false;


        }
          }
     }

    }

当前用于拒绝未选择的无线电按钮的代码:

if (document.ExamEntry.examtype.checked){
      alert('checked') //for testing if statement runs when appropriate//
} 

else {
msg+="You must enter the exam type \n";
result = false;
}

2 个答案:

答案 0 :(得分:0)

以下是有关如何验证radioboxes的示例代码:http://jsfiddle.net/jyUAM/3/

<script type="text/javascript">
function validateRadioboxesByName(form, name)
{
    var el = form[name];
    for (i = 0; i < el.length; ++i) {
        if (el[i].checked)
            return true;
    }

    return false;
}

function checkRegistration() {
    var isValid = validateRadioboxesByName(document.forms.test, "examtype");

    if (!isValid)
        alert("Please check one of the radiobox.");

    return isValid;
}
</script>

<form name="test" onsubmit="return checkRegistration()">
    <input type="radio" name="examtype" value="GCSE"/>GCSE

    <input type="radio" name="examtype" value="AS"/> AS

    <input type="radio" name="examtype" value="A2"/> A2

    <button type="submit">Send</button>
</form>

这样您就不需要记住点击的radiobox的状态,只需在需要数据时询问浏览器,即在提交数据之前。

本教程可能会为您提供有关如何向用户显示消息的更多提示,而不是使用丑陋的alert调用:http://www.the-art-of-web.com/html/html5-checkbox-required/

最后一个链接上的示例用于复选框不应该吓到你,你可以轻松地将它们应用到无线电输入框等。

答案 1 :(得分:0)

尝试在两个函数外部将变量设置为false,然后如果确认函数运行,则将该变量赋值为true。

然后在您检查用户是否单击了单选按钮的下一个函数中,使用仅在变量设置为false(可能包含警报消息)时运行的if语句。

希望这会有所帮助:)