单选按钮验证

时间:2013-09-30 06:42:28

标签: javascript html

我正在尝试使用JavaScript / HTML来验证几个单选按钮,但我遇到了问题。我遇到麻烦的脚本如下 -

        if ( ( RegistrationForm.sexm[0].checked == false ) && ( RegistrationForm.sexf[1].checked == false )) 
        {
            alert( "Please select your sex" ); 
            return false;
        }

基本上,如果没有选择单选按钮选项,我希望它返回警报。在提交表单时,表单会刷新并且不提供任何警报。任何建议将不胜感激!

我提供的相关HTML是 -

<form id="RegistrationForm" onsubmit="ValidateForm()" action="">
 <fieldset>
  <legend>Registration Form</legend>
    <label for="username">User Name: </label> 
    <input type="text" class="input" id="username"/><br />
    <label for="password">Password: </label> 
    <input type="password" class="input" id="password"/><br />
    <label for="repassword">Re-Type Password: </label> 
    <input type="password" class="input" id="repassword"/><br />
    <label for="email">Email Address: </label> 
    <input type="text" class="input" size="30" id="email"/><br />
    <label>Age: </label> 
    <select id ="age" name="age">
        <option value=""> --- </option>
        <option value="0-18">0-18</option>
        <option value="18-30">18-30</option>
        <option value="30-50">30-50</option>
        <option value="50+">50+</option>
    </select><br/>
    <label for="sexm">Sex:</label>
    <input type="radio" id="sexm" name="sex" value="male" />Male<br/>
    <label for="sexf">&nbsp; </label>
    <input type="radio" id="sexf" name="sex" value="female" />Female<br/>   
    <input type="checkbox" name="agree"  id="agree" value="agree"/>
    <label for="agree">I accept the <a href="">terms and cond</a>.</label> <br/>
    <label>&nbsp; </label> 
    <input type="submit" value="Submit" class="button" /> 
 </fieldset>
</form>

3 个答案:

答案 0 :(得分:2)

在javascript <script>标记

中试用此代码
function ValidateForm () {
   if ( ( document.getElementById("sexm").checked == false ) && ( document.getElementById("sexm").checked == false )) 
   {
      alert( "Please select your sex" ); 
      return false;
   } else {
      return true;
   }
}

将其替换为您的代码

if ( ( RegistrationForm.sexm[0].checked == false ) && ( RegistrationForm.sexf[1].checked == false )) 
{
    alert( "Please select your sex" );
    return false;
}

答案 1 :(得分:1)

使用for循环来检查您的用户是否选择了任何值,如果没有,则抛出警报并使用return false来阻止您的表单被提交。

Demo

var ischecked = null;
var radios = document.getElementsByName('sex');
for (var i = 0; i < radios.length; i++) {
          if (radios[i].checked) {
           ischecked = radios[i];
   }
}
if(ischecked==null) {
    alert('Please choose your Sex');
    return false;
}

将上述代码保存在函数中,并在提交表单时调用它。


Demo 2(提交时验证)

  

注意:您需要使用onsubmit="return ValidateForm();"

答案 2 :(得分:0)

试试这个......

<script type="text/javascript">
function validate()
{
var o = document.getElementById('sexm');
var t = document.getElementById('sexf');

if ( (o.checked == false ) && (t.checked == false ) )
{
alert ("please select your sex" );

return false;
}
return true;
}
</script>