2012-03-15 181 views
1

我已經在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代碼將檢查用戶名和密碼是否登錄表單上輸入與否。它工作正常。但是在顯示錯誤之後,它會提交表單。

我希望不要提交此表格,如果用戶名和密碼沒有輸入。它應該停留在登錄頁面上。我怎樣才能做到這一點?

回答

2

嘗試:

 

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();"> 
 

希望它可以幫助

+0

啊哈......感謝的人。我很傻。我怎樣才能忘記退貨聲明? :D感謝buddy它的工作.. :) – 2012-03-15 11:21:28

+0

很高興知道它爲你工作..你可以標記答案爲接受.. :) – 2012-03-15 11:22:20

+0

亞肯定..已經:) – 2012-03-15 11:25:11