Hak*_*kan 2 forms validation jquery
有人可以告诉我为什么下面的代码不起作用.它应该提醒它.但即使字段为空,它也会在之后返回true.
<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>
Run Code Online (Sandbox Code Playgroud)
你是从.each()
回调函数返回的,一个return false
中断,但不从外部函数(你的submit
处理程序)返回,而是你应该做这样的事情:
$('#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;
});
Run Code Online (Sandbox Code Playgroud)
在这里它找到第一个空元素,设置result
to false
并在一个语句中返回,然后result
从外部函数返回...如果没有空字段,这仍然是true
.
归档时间: |
|
查看次数: |
6545 次 |
最近记录: |