2014-07-25 34 views
0

這是我的javascript代碼,用於檢查用戶是否輸入了用戶名和密碼字段的值。當我運行這個,它顯示我正確的警報消息,但表單似乎被提交,即使它返回false。有人可以幫助我嗎?提交時Javascript錯誤重定向

<script type="text/javascript"> 
    function loginValidate(){ 
     if (document.getElementById("username").value==''){ 
      window.alert("Please enter your username"); 
      if (document.getElementById("password").value==''){ 
       window.alert("Please enter your username and password"); 
     return false; 
      } 
     } 
     if (document.getElementById("password").value==''){ 
      window.alert("Please enter your password"); 
     return false; 
     } 

    return true; 
    } 
</script> 

<form onsubmit="loginValidate()"> 
<input type="submit" name="submit" id="submit" value="Login" /> 
</form 

回答

2

您需要返回由該函數返回的句柄值:

<form onsubmit="return loginValidate()"> 

而且,不提供任何形式的控制「提交」作爲其分配給一個參考的名稱或ID控件向表單的提交屬性,從而掩蓋表單的提交方法(即form.submit引用該控件,因此form.submit()將失敗)。

很少有任何需要一個提交按鈕有一個名稱或ID,所以:

<input type="submit" value="Login"> 

您還可以清理邏輯位。如果傳遞給函數的形式的參考,得到了控制更容易:

<script> 
    function loginValidate(form){ 
    if (form.username.value == ''){ 
     window.alert("Please enter your username"); 
     return false; 
    } 

    if (form.password.value == ''){ 
     window.alert("Please enter your password"); 
     return false; 
    } 
    return true; 
    } 
</script> 

<form onsubmit="return loginValidate(this)"> 
    <table> 
    <tr><td>Username: <td><input type="text" name="username"> 
    <tr><td>Password: <td><input type="password" name="password"> 
    <tr><td colspan="2" style="text-align: right;><input type="submit" value="Login"> 
    </table> 
</form 

注意,這以明文發送的密碼,因此不是特別安全。

+0

Thnx很多!!!!!有效。試了幾次來修復它。 Thnx再次。 – user3194672

+0

如果它工作我的朋友,然後接受答案是正確的。 –

+0

@ user3194672請閱讀以下關於問題和答案的頁面http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –