Reputation: 63
Frnds i need some help.. In this code i have validated the 2 textboxes. The help i need is once no data has been entered in the boxes the form should not goto check.php but with an javascript alert: Invalid Data I need this in Javascript...
function f1()
{
var v1=document.getElementById("uname").value;
var v2=document.getElementById("pass").value;
if(v1=="" || v2=="")
alert("Please Fill It..!");
}
Username:<input type="text" id="uname" placeholder="username" title="Enter your Username" name="uname"/>
Password:
<input type="password" id="pass" placeholder="password" title="Enter your password" name="pass"/>
<input type="submit" value="Login"/>
<input type="reset" value="clear"/>
</form>
Upvotes: 0
Views: 4934
Reputation: 1511
Try this:
function f1()
{
var v1=document.getElementById("uname").value;
var v2=document.getElementById("pass").value;
if(v1=="" || v2=="")
{
alert("Please Fill It..!");
return false;
}
}
The problem with your function is that by default it returns true and form is submitted. You need to return false in order to prevent form submit.
Upvotes: 1
Reputation: 20544
You can use the attribute onSubmit
which will run the javascript in it. If it returns a falsy value, the submit won't be made, but if it returns true
, the submit will be made.
<form method="POST" onSubmit="return f1()">
Username:<input type="text" id="uname" placeholder="username" title="Enter your Username" name="uname"/>
Password:
<input type="password" id="pass" placeholder="password" title="Enter your password" name="pass"/>
<input type="submit" value="Login"/>
<input type="reset" value="clear"/>
</form>
f1 has to be a function that returns true
or false
Upvotes: 0
Reputation: 2257
you need to register your f1() as form onSubmit event handler.
<form action="formaction" method="post" onsubmit="f1()">
Username:<input type="text" id="uname" placeholder="username" title="Enter your Username" name="uname"/>
Password:
<input type="password" id="pass" placeholder="password" title="Enter your password" name="pass"/>
<input type="submit" value="Login"/>
<input type="reset" value="clear"/>
</form>
function f1()
{
var v1=document.getElementById("uname").value;
var v2=document.getElementById("pass").value;
if(v1=="" || v2=="") return false;
}
Upvotes: 0