Form validation with jquery - return false
Can some one tell my why the folowing code doesn't work. It alerts as it should. But it return true afterwards, even if a field is empty.
<form id="theform" method="post" action="mailme.php">
<input id="field1" name="a" value="field1" type="text" />
<input id="field开发者_高级运维2" name="b" value="field2" type="text" />
<input id="field3" name="c" value="field3" type="text" />
<input id="field4" name="d" value="field4" type="text" />
<input type="submit" />
</form>
<script>
$('#theform').submit(function(){
$('#theform input[type=text]').each(function(n,element){
if ($(element).val()=='') {
alert('The ' + element.id+' must have a value');
return false;
}
});
return true;
});
</script>
You're returning from the .each()
callback function, a return false
breaks that, but doesn't return from the outer function (your submit
handler), instead you should do something like this:
$('#theform').submit(function(){
var result = true;
$('#theform input[type=text]').each(function(n,element){
if ($(element).val()=='') {
alert('The ' + element.id + ' must have a value');
return result = false;
}
});
return result;
});
In this it finds the first empty element , sets the result
to false
and returns in one statement, then returns the result
from the outer function...if there were no empty fields, this would still be true
.
You can also use jQuery's filter()
function with a callback function, and then testing the resulting array for its size, returning true
if it's zero.
$('#theform').submit(function(event) {
var filtered = $('#theform input[type=text]').filter(function(index) {
if ($(this).val() == '') {
alert('The ' + this.id + ' must have a value');
return true;
}
return false;
});
return filtered.length == 0;
});
Your two return statements are in different contexts, so your each function returns false, but that is not the same as a return statement for your submit function, which will always return true on the last line.
精彩评论