JQuery Form Validation – .submit function

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&gt;
<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>

Like This!

Advertisements
Tagged with:
Posted in JQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: