Aishwarya Shiva Aishwarya Shiva - 4 months ago 12
HTML Question

How to block form submit?

I have following code in 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");
}
}


and HTML code as

<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>


The JavaScript code checks whether the username and password are entered on login form or not. It is working fine. But after showing error, it submits the form.

I want that this form should not be submitted if username and password are not entered. It should just stay on login page. How can I achieve this?

Answer

Try:


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;
   }
}

And on your onsubmit:


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

Hope it helps