JQuery makes form validation a snap with the .submit function. The example below is fairly self explanatory. In brief we place the .submit function in the .docready function, use .after to add text after any empty form fields with the css class .required.
<html>
<head>
<style>
.error{color:#f00;}
</style>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>
<script type=”text/javascript”>
$(function() {
$(‘#form1′).submit(function(){
if($(‘#firstname’).val() == ”){
$(‘#firstname’).after(‘<p><span>please enter a first name.</span></p>’);
$(‘#firstname’).focus();
return false;
}
if($(‘#lastname’).val() == ”){
$(‘#lastname’).after(‘<p><span>please enter a last name</span></p>’);
$(‘#lastname’).focus();
return false;
}
});
// onchange for text fields
$(‘.required’).blur(function(){
if($(‘.required’).val() !== ”){
$(‘.error’).remove();
}
});
// ends doc ready
});
</script>
</head>
<body>
<form name=”form1″ id=”form1″ action=”index.html” method=”post”>
<p>First name: <input type=”text” name=”firstname” id=”firstname” /></p>
<p>Last name: <input type=”text” name=”lastname” id=”lastname” /></p>
<input type=”submit” value=”Submit” />
</form>
</body>
</html>
