Reputation: 25
This is my login form saved as n_form.html. I am trying to check empty fields but whenever I click login without filling the fields my form redirects to the next page instead of giving a message. Please help.
<!DOCTYPE html>
<html>
<head>
<title>Registration Form Of Teknack</title>
<link rel="stylesheet" type="text/css" media="screen" href="css-page.css" />
<script language="Javascript">
function validateForm(){
var x=document.forms["n_form"]["Username"].value;
var y=document.forms["n_form"]["Password"].value;
if (x==null || x=="" & y==null || y==" "){
alert("Form must be filled.");
return false;
}
}
</script>
</head>
<body>
<br><br><br>
<form name="n_form" action="form.php" onclick="return validateForm()" method="post">
<ol>
<li>Username<br>
<input id="width" type="text" name="name" value="" /></li>
<li><br>Password<br>
<input id="width" type="password" name="password" value="" /></li>
<li><br>
<input type="checkbox" value="">Remember me<br></li>
<li id="login">
<br><button type="submit">Login</button></li>
</ol>
</form>
</body>
</html>
Thanks in advance,
Upvotes: 0
Views: 7394
Reputation: 3972
I strongly recommend to use jQuery instead Javascript! Get and learn. However this is answer:
Tutorial demos of jQuery validations and forms: http://speckyboy.com/2009/12/17/10-useful-jquery-form-validation-techniques-and-tutorials-2/
A solution in Javascript:
Javascript code:
<script language="javascript">
function validateForm(form)
{
var username=getElementbyId('username').value;
var password=getElementbyId('password').value;
if(username == "")
{
alert("You must fill up username!");
}
else if (password == "")
{
alert("You must fill up password!");
}
else
{
// nothing, okay status...
}
// or if you want to show a message on one of empty field:
if (username == "" || password == "")
{
alert("You must fill up a form");
}
else
{
// nothing, okay status...
}
}
And change in a HTML FORM:
<li>Username<br>
<input id="username" type="text" name="username" value="" />
</li>
<li><br>Password<br>
<input id="password" type="password" name="password" value="" />
</li>
<li><br><input type="checkbox" value="">Remember me<br>
</li>
<li id="login">
<br><button type="button" onclick="check(this.form)">Login</button>
</li>
Upvotes: 1
Reputation: 20313
Try:
function validateForm()
{
var x=document.n_form.name.value;
var y=document.n_form.password.value;
if (x==null || x=="" && y==null || y=="")
{
alert("Form must be filled.");
return false;
}
}
Upvotes: 1