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="field2" 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 can also use jQuery’s
filter()function with a callback function, and then testing the resulting array for its size, returningtrueif it’s zero.