Created
September 2, 2011 14:34
-
-
Save victorbstan/1188754 to your computer and use it in GitHub Desktop.
Use jQuery to check if certain form fields have a value before submitting the form.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta http-equiv="Content-type" content="text/html; charset=utf-8"> | |
<title>Validation</title> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> | |
</head> | |
<body> | |
<div class="error"> | |
Please fill in all required field and submit the form again: | |
<ul> | |
<li>First Name</li> | |
<li>Last Name</li> | |
<li>Email</li> | |
<li>Phone</li> | |
</ul> | |
</div> | |
<form action="" method="get" accept-charset="utf-8"> | |
Required: | |
<br/> | |
1 <input type="text" name="a" value="" id="a" class="required"> | |
<br/> | |
2 <input type="text" name="b" value="" id="b" class="required"> | |
<br/> | |
3 <input type="text" name="c" value="" id="c" class="required"> | |
<p><input type="submit" class="submit" value="Continue →"></p> | |
</form> | |
<script type="text/javascript" charset="utf-8"> | |
$(document).ready(function() { | |
$('.error').hide(); | |
$('.submit').click(function(event) { | |
$('.required').each(function (i, el) { | |
var data = $(el).val(); | |
// console.log(i + ': ' + data); | |
var len = data.length; | |
if (len<1) { | |
$('.error').show(); | |
$('html, body').animate({scrollTop:0}, 'slow'); | |
event.preventDefault(); | |
return; | |
} | |
}); | |
}); | |
}); | |
</script> | |
</body> | |
<html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jklkjlklkj