如何阻止表单提交?

时间:2012-03-15 11:09:50

标签: javascript html forms

我在JavaScript中有以下代码

function checkEntries()
{
    if(document.getElementById("username")=="" &&  document.getElementById("password").value=="")
    {
        alert("Please enter username and password");
    }
    if(document.getElementById("username").value=="")
    {
        alert("Please enter username");
    }
    if( document.getElementById("password").value=="")
    {
        alert("Please enter password");
    }
}

和HTML代码

<form name="LoginUser" method="post" action="LoginUser" onsubmit="checkEntries()">
              <table width="78%" height="90" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td width="47%" align="right" class="textstyle">Username:
                  <label for="username2"></label></td>
                <td width="53%" class="textstyle">
                  <input type="text" name="username" id="username" /><div id="testuser"></div>
                </td>
              </tr>
              <tr>
                <td align="right" class="textstyle">&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
              <tr id="passRow">
                <td align="right" class="textstyle">Password:</td>
                <td><label for="password"></label>
                  <input type="password" name="password" id="password"/>
Forgot Password?? Click here...               
<div id="testpwd"></div></td>
              </tr>
              <tr>
                <td align="right" class="textstyle">&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td align="right" class="textstyle">&nbsp;</td>
                <td><input type="checkbox" name="rempass" id="rempass" />
                  <span class="textstyle">Remember my password</span></td>
              </tr>
              <tr>
                <td align="right" class="textstyle">&nbsp;</td>
                <td class="textstyle">&nbsp;</td>
              </tr>
              <tr>
                <td align="right" class="textstyle">&nbsp;</td>
                <td class="textstyle">
                  <input type="submit" name="login" id="login" value="Sign in" />
                  </td>
              </tr>
            </table>
        </form>

JavaScript代码检查是否在登录表单中输入了用户名和密码。它工作正常。但在显示错误后,它会提交表单。

我希望如果未输入用户名和密码,则不应提交此表单。它应该只停留在登录页面上。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:3)

尝试:


function checkEntries() {
   var errFlag = false;
   var errMsg = "";
    var username = document.getElementById("username");
    var password = document.getElementById("password")
   if(username == "") {
      errMsg += "Please enter username.\n";
      errFlag = true;
   }
   if(password == "") {
     errMsg += "Please enter password";
     errFlag = true;
   }
   if(!errFlag) {
      return true;
   }else {
      alert(errMsg);
      return false;
   }
}

在你的onsubmit上:


<form name="LoginUser" method="post" action="LoginUser" onsubmit="return checkEntries();">

希望有所帮助