2011-02-16 71 views
0

我目前有一個由一個表單,5個類別,每個類別中的一堆問題和每個問題的少數單選按鈕答案組成的大型民意調查。這些類別分別處於不同的字段集中,並且每個類別都需要表單處理的最低票數。我試圖讓jQuery通過一個.each()循環遍歷每個字段集,並決定是否滿足每個類別的最小投票數,如果不滿足,則取消表單提交。到目前爲止,我所處理的類別都很好,但如果有必要,不會阻止表單提交。取消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(); 
     } 
    }); 

}); 

任何想法?

回答

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; 
}); 

我沒有測試這段代碼。

0

return false;第二個最後});剛剛過後,你只需要返回false一次,而不是每次都循環通過那個each()函數。

+0

在第二個最後一個`})之後加入`return false;``不管最低投票數是否投出, – John 2011-02-16 08:00:37