onSubmit事件没有任何反应

时间:2013-09-20 22:39:37

标签: javascript css xhtml

这是我的代码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <script type = "text/javascript">
          function validate(){
              var warnings = "some warnings";               
              document.getElementById("alert").innerHTML = warnings;
              document.getElementById("alert").styledisplay = "block";
              return true;
          }
        </script>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
      </head>
      <body>
        <div id = "alert"></div>
        <div id = wrapper>
          <h2>Enter Your Info</h2>
          <form name = "myForm" onSubmit = "javascript:validate()">
        <div>
          <label for = "username">User Name:</label>
          <input type = "text" name = "username" id = "username"/>
        </div>
        <div>
          <label for = "firstname">First Name:</label>
          <input type = "text" name = "firstname" id = "firstname"/>
        </div>
        <div>
          <label for = "lastname">Last Name:</label>
          <input type = "text" name = "lastname" id = "lastname"/>
        </div>
        <div>
          <label for = "password">Password:</label>
          <input type = "password" name = "password" id = "password"/>
         </div>
        <div>
          <input type = "submit" value = "submit" id = "submit"/>
        </div>
          </form>
        </div>
      </body>
    </html>

我遇到的问题是当我点击提交按钮时没有任何反应。不知道为什么,我对java脚本和HTML很新,但是我读过的所有内容都说应该可以使用任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:2)

您总是返回true。所以表格会提交。相反,试试这个:

<form name="myForm" onSubmit="return validate()">

 function validate() {

     var warnings  = validate();

     document.getElementById("alert").innerHTML = warnings;
     document.getElementById("alert").styledisplay = "block";
     if(warnings) return false; //If any warning i don't want to submit.
     return true;
 }

只是为了补充。 if(warnings)将根据您设置的初始警告状态失败,或者从验证函数中设置任何内容(如果验证成功)返回空字符串或返回null,未定义等或只返回任何内容...

相关问题