JavaScript验证表单/不工作

时间:2016-04-16 04:30:48

标签: javascript

绝对的新手在这里 - 我对编码充满热情,上周刚开始使用Javascript ......我似乎无法通过此验证工作!提前感谢您的所有好建议

-S

 <script type="text/javascript">
            //Registration Form Validation
                function validate(){

             var firstName=document.getElementById("name").value;
             var maleUser = document.getElementById("maleButton").checked;


             if(firstName=="" || firstName==" "){
                 alert("Please enter your first name: ");

                  return false;
            }

else  if(maleUser==false){
                alert("Please select your gender: ");

            }else{

                return true; window.location.href="Search/index.htm";

          </script>

    <!-- Reg Form needing validation -->
           <h1>Registration Form</h1>
              <p>
              <div class=form_settings>
              <form name="RegForm" onsubmit="return(validate());" >
        First name: <input type="text" name="first_name" id="name" placeholder="Enter your First name" size="35"/>
        <br>
        Gender:
        <input type="radio" name="male" id="maleButton" value="male"> Male
        <br>
         </p>
                  </form>

2 个答案:

答案 0 :(得分:1)

我运行了你的代码并获得了

  

未捕获的SyntaxError:意外的输入结束

第20行

在你的其他地方

之后你错过了一个}
else{

            return true; window.location.href="Search/index.htm";

Protip:以chrome运行并输入CTRL-SHIFT-J

答案 1 :(得分:1)

请更正您的HTML代码:

<h1>Registration Form</h1>  
<div class="form_settings">
  <form name="RegForm" action="search/index.htm">
    First name: 
    <input type="text" name="first_name" id="name" placeholder="Enter your First name" size="35"/>
    <br>
    Gender:
    <input type="radio" name="male" id="maleButton" value="male"> Male
    <br>
    <input type="submit" value="submit" onclick="return(validate());">
  </form>
</div>

添加此更新的JavaScript代码:

function trim(str) {

   return str.replace(/^\s+|\s+$/g,"");
}

function validate(){

  var firstName = document.getElementById("name").value;
  var maleUser = document.getElementById("maleButton").checked;

  if (trim(firstName) === ''){

    alert("Please enter your first name: ");

    return false;
  }
  else if(maleUser == false){

    alert("Please select your gender: ");

    return false;
  }
  else{

    //window.location.href="Search/index.htm";
    return true; 
  }
}

您可以在此处查看完整的结果:https://jsfiddle.net/logual/ba5f7tkw/

请勿使用window.location.href提交表单。添加带有网址的action属性和表单的提交按钮。