I guess you are trying to provide feedback to the user as he/she fills out the form by coloring the fields. Then also safeguarding against submitting the form while there are still form fields that are used incorrectly.
For checking a field when a user exits the field you can use 'onblur' on the fields. For safeguarding against incorrect forms being submitted you can use a function which returns a boolean in the 'onsubmit' event of the form.
Hope this helps.
Kind regards,
Ryan.
Code:
<html>
<head>
<title></title>
</head>
<script type="text/javascript">
var red = "#FFB0B0";
var green = "#B0FFB0";
function emailForm()
{
var x=document.forms["contact"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
document.contact.email.style.backgroundColor = red;
return false;
}else{
document.contact.email.style.backgroundColor = green;
return true;
}
}//end email Form
function ageForm()
{
if (parseInt(document.contact.age.value) < 18 ||
parseInt(document.contact.age.value) > 65)
{
document.contact.age.style.backgroundColor = red;
return false;
}else{
document.contact.age.style.backgroundColor = green;
return true;
}
}//end of age form
function ValidateFormFields(){
var bSend = false
if (emailForm() && ageForm()){
// if both fields are correnct allow submit to continue
bSend = true;
}
if (!bSend) { alert("please correct the form") };
return bSend;
}
</script>
<body>
<form name="contact" onsubmit="return ValidateFormFields(); " action="http://www.google.com">
<p>Email:
<input type="text" name="email" onblur="emailForm()">
</p>
<p>Age:
<input type="text" name="age" onblur="ageForm()">
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
</body>
</html>
Bookmarks