我目前有一个由一个表格,5个类别组成的大型投票,每个类别中有一堆问题,每个问题都有几个单选按钮答案。每个类别都在不同的字段集中,并且每个类别需要不同的最小票数才能处理表单。
基本上,在表单提交时,我尝试让jQuery使用.each()循环检查每个字段集,并确定是否达到了每个类别的最小投票数,如果没有,则取消表单提交。到目前为止,我已经处理好了类别,但不会阻止表单在必要时提交。
$('#pollform').submit(function(event){
var formsubmit = event;
$('fieldset').each(function(formsubmit){
catname = $(this).children('input[name=catname]').val(); // Category name
reqvotes = $(this).children('input[name=catcount]').val(); // Minimum required number of votes for current category in loop
numvotes = $(this).children(':checked').size(); // Number of votes for current category in loop
// Check minimum number of votes against actual number cast. Alert user and prevent form from submitting if necessary
if (reqvotes > numvotes)
{
alert('You need to fill out at least ' + reqvotes + ' items for ' + catname + '.');
formsubmit.preventDefault();
}
});
});有什么想法吗?
发布于 2011-02-16 15:03:02
你有没有尝试过返回false?当然,您必须在each循环之外执行此操作。
$('#pollform').submit(function(event){
var stopsubmit = false;
$('fieldset').each(function(formsubmit){
if(stopsubmit) return;
catname = $(this).children('input[name=catname]').val(); // Category name
reqvotes = $(this).children('input[name=catcount]').val(); // Minimum required number of votes for current category in loop
numvotes = $(this).children(':checked').size(); // Number of votes for current category in loop
// Check minimum number of votes against actual number cast. Alert user and prevent form from submitting if necessary
if (reqvotes > numvotes)
{
alert('You need to fill out at least ' + reqvotes + ' items for ' + catname + '.');
stopsubmit=true;
}
});
if(stopsubmit) return false;
});我没有测试这段代码。
发布于 2011-02-16 15:53:23
在倒数第二个});之后添加return false;,您只需返回false一次,而不是在遍历该each()函数时每次返回false。
https://stackoverflow.com/questions/5013412
复制相似问题