【问题标题】:Cancelling form submission within jQuery .each() loop在 jQuery .each() 循环中取消表单提交
【发布时间】:2011-02-16 07:00:12
【问题描述】:

我目前有一个大型民意调查,由一个表单、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();
        }
    });

});

有什么想法吗?

【问题讨论】:

    标签: jquery forms loops each


    【解决方案1】:

    你试过只返回 false 吗?当然,你必须在每个循环之外这样做。

    $('#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;
    });
    

    我没有测试这段代码。

    【讨论】:

      【解决方案2】:

      在倒数第二个}); 之后添加return false;,您只需返回一次false,而不是每次循环通过该each() 函数时。

      【讨论】:

      • 在倒数第二个 }); 之后添加 return false; 只会阻止表单提交,无论是否达到最低投票数。
      猜你喜欢
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      相关资源
      最近更新 更多