I want to have a real-time validation for the first name & last name to check if user entered the data before submit.
Well it's work fine in Google Chrome...
But in Firefox & Internet Explorer, if user press "Tab" key in "first name",
then the alert message will keep LOOPING between "first name" & "last name"
to perform the validation n thus infinite alert message keep pop-up.
Same apply when user press "Tab" key in "last name" & another LOOPING start.
Wondering how the "setTimeout" stuff works...
Here's my code, thanks a million =)
<head>
<title>Form</title>
<script type="text/javascript">
function FN(field) {
var chkFN = field.value;
if (chkFN == null || chkFN == "") {
alert("First name must fill !");
setTimeout( function() { field.focus(); field.select(); }, 50);
// setTimeout(0, 50);
// field.focus();
// field.select();
return false;
}
return true;
}
function LN(field) {
var chkLN = field.value;
if (chkLN == null || chkLN == "") {
alert("Last name must fill !");
setTimeout( function() { field.focus(); field.select(); }, 50);
// setTimeout(0, 50);
// field.focus();
// field.select();
return false;
}
return true;
}
function EA(field) {
var chkEA = field.value;
if (chkEA == null || chkEA == "") {
alert("Email must fill !");
setTimeout( function() { field.focus(); field.select(); }, 50);
// setTimeout(0, 50);
// field.focus();
// field.select();
return false;
}
return true;
}
function validate(form) {
var chkFN = document.forms["sendForm"]["txtFirstName"].value;
if (chkFN == null || chkFN == "") {
alert("First name must fill !");
form.txtFirstName.focus();
form.txtFirstName.select();
return false;
}
var chkLN = document.forms["sendForm"]["txtLastName"].value;
if (chkLN == null || chkLN == "") {
alert("Last name must fill !");
form.txtLastName.focus();
form.txtLastName.select();
return false;
}
var chkEA = document.forms["sendForm"]["txtEmail"].value;
if (chkEA == null || chkEA == "") {
alert("Email must fill !");
form.txtEmail.focus();
form.txtEmail.select();
return false;
}
}
</script>
</head>
<body>
<form name="sendForm" id="sendForm" onsubmit="return validate(this)">
<table>
<tr>
<td>First Name</td>
<td>
<input class="input" type="text" name="txtFirstName" id="txtFirstName"
onblur="FN(this)" onchange="validate(this)" />
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input class="input" type="text" name="txtLastName" id="txtLastName"
onblur="LN(this)" onchange="validate(this)" />
</td>
</tr>
<tr>
<td>Email</td>
<td>
<input class="input" type="text" name="txtEmail" id="txtEmail"
onblur="EA(this)" onchange="validate(this)" />
</td>
</tr>
<tr>
<td><input type="reset" value="Reset Form" title="Reset form" /></td>
<td><input type="submit" value="Submit Form" title="Submit form" /></td>
</tr>
</table>
</form>
</body>
</html>