如果在使用jquery的.each()函数遍历每个表单元素后验证失败,则阻止表单提交 [英] prevent form submission if validation failed after iterating over each form element with jquery's .each() function
问题描述
我有以下代码,其中我尝试遍历html文本输入元素,进行一些验证,并在验证失败时阻止表单提交:
I have the following code in which I'm trying to iterated over html text input elements, do some validation and prevent the form submission if the validation fails:
$("#the_form").submit(function(){
$(":text", this).each(function(){
if($(this).val().length != 0)
{
var str = $(this).val();
str = $.trim($(this).val());
$(this).val(str);
if($(this).val().length < 4)
{
alert("You should enter at least 4 characters");
$(this).focus();
return false;
}
}
}) // end of each() function
return true;
})
如果删除.each()函数并单独执行每个元素(这显然不是一种很好的方法),则会得到想要的结果.但是,如果我按原样使用代码,即使用户没有输入至少四个字符,表单也会继续提交.关于我可能在这里做错的任何想法?任何帮助将不胜感激.预先感谢.
If I remove the .each() function and do each element separately (which obviously is not a very good approach), I get the results wanted. However, if I use the code as it is, the form keeps on submitting even if the user has not entered at leas four characters. Any ideas on what I may be doing wrong here? Any help will be very appreciated. Thanks in advance.
推荐答案
您的return false;
来自$.each()
的回调函数中(这会使它在该迭代中中断),而不是来自submit
处理程序(将停止表单提交).这应该可以解决问题:
Your return false;
is from within the callback function for $.each()
(which makes it break at that iteration) and not from the submit
handler (which would stop the form submission). This should do the trick:
$("#the_form").submit(function(){
var isValid = true;
$(":text", this).each(function(){
if($(this).val().length != 0)
{
var str = $(this).val();
str = $.trim($(this).val());
$(this).val(str);
if($(this).val().length < 4)
{
alert("You should enter at least 4 characters");
$(this).focus();
isValid = false;
return false;
}
}
}) // end of each() function
return isValid;
})
这篇关于如果在使用jquery的.each()函数遍历每个表单元素后验证失败,则阻止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!