Best thing I like about jquery is each() function which loops the jquery elements and do the best for you. For code reusability I'm posting this article to show how with one javascript function we could confirm that all our required fields are not empty when submitting the form.
First say we have a registration form for reservation application, we have some fields must be requied, others must only contains a valid email address and others are optional. So without considering any calling for our confirm function we will only mark out input fields. Here is how to do:
<input type=text runat=server alt=required />
<input type=text runat=server alt=email />
<input type=text runat=server />
The first input is required, the second one must contain a valid email address while the last is optional.
Now in our javascript file , lay out these few lines of code:
$(document).ready(function(){
$('form').onsubmit(function(){
var success = true;
$('input[alt=required]').each(function(){
if($(this).val() == ''){
success = false;
}
});
if(!sucess)
alert('Fill in all required fields before submitting.');
return validateEmails();
});
});
function validateEmails()
{
var success = true;
var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$('input[alt=email]').each(function(){
if(!emailFilter.test($(this).val()) ){
success = false;
}
if(!success)
alert('You must enter a valid email address');
return success;
}
Save this file and link it to any page you wanna validate before submitting and don't forget linking to jquery source.
Cool isn't it?
b8713648-6477-4523-ac96-14dee591c57b|0|.0