2015-05-04 168 views
0

我有一個表,我遍歷每一行。 如果行背景顏色爲綠色,並且其各自的複選框以classbox作爲linebox未被選中,我應該在點擊提交時顯示錯誤消息。 但返回false不起作用,表單正在提交。儘管消息正在顯示。 我該如何解決這個問題? 以下是代碼。jQuery返回false不工作

jQuery(document).on('click', '#add-All-button', function() { 
    $(".rowb").each(function() {      
    if($(this).css("background-color") == "rgb(71, 163, 71)") { 
     var ischk = 0; 
     var row = $(this);       
     if (row.find('input[class="linebox"]').is(':checked')) { 
     ischk++; 
     } 
     if(ischk==0) { 
     alert('Every green colored row should have one of the checkboxes checked.'); 
     return false; 
     } 
    }      
    }); 
}); 

回答

2

您需要在外部函數中返回false,在.each中返回false將僅打破循環。另一個可能需要用來停止表單提交的工具是event.preventDefault,它可以用來停止瀏覽器的默認行爲,如轉到鏈接或提交成形,但您需要更改按鈕上的事件類型以適當地匹配。也就是說,您應該傾聽的事件是提交的。查看下面的固定代碼以獲取更多詳細信息。

jQuery(document).on('submit', '#add-All-button', function() { 
    var out = true; 
    $(".rowb").each(function() { 
     if ($(this).css("background-color") == "rgb(71, 163, 71)") { 
      var ischk = 0; 
      var row = $(this); 
      if (row.find('input[class="linebox"]').is(':checked')) { 
       ischk++; 
      } 
      if (ischk == 0) { 
       alert('Every green colored row should have one of the checkboxes checked.'); 
       out = false; 
      } 
     } 
    }); 
    if (!out) { event.preventDefault(); } 
    return out; 
}); 
+0

謝謝Shane!上述代碼在條件爲真時不起作用。它總是阻止表單提交。 – Viral

+0

你可以使用event.preventDefault()來停止表單提交請參閱上面的編輯 – ShaneQful

+0

謝謝謝恩......它解決了這個問題。非常感謝。 – Viral

7

你沒有返回false你的事件處理程序的,只是你的$.each回調。如果您還想從處理程序中返回false,則在處理程序本身中需要一個return語句。

例如,可能(見***線):

jQuery(document).on('click', '#add-All-button', function() { 
    var rv; // *** By default it's `undefined`, which has no special meaning, so that's fine 
    $(".rowb").each(function() { 
     if ($(this).css("background-color") == "rgb(71, 163, 71)") { 
      var ischk = 0; 
      var row = $(this); 
      if (row.find('input[class="linebox"]').is(':checked')) { 
       ischk++; 
      } 
      if (ischk == 0) { 
       alert('Every green colored row should have one of the checkboxes checked.'); 
       rv = false; // *** 
       return false; 
      } 
     } 
    }); 
    return rv; // *** 
}); 

邊注:這種比較很可能在野外失敗:

$(this).css("background-color") == "rgb(71, 163, 71)" 

不同的瀏覽器返回的顏色信息以不同的格式,並且不要以您在(必要)中設置的相同格式返回值。 jQuery不會試圖對此進行標準化。所以你回來的價值可能是"rgb(71, 163, 71)",但它也可能是"rgb(71,163,71)""rgba(71, 163, 71, 0)""rgba(71,163,71,0)"或甚至"#47A347"。而不是依靠以特定格式獲取價值,您最好使用data-*屬性或通過jQuery data函數跟蹤的值。


附註2:我不會用click事件按鈕掛接到表單提交過程;我會使用formsubmit事件。

+0

感謝Crowder!你給了我一些非常好的信息。但是,當條件爲真時,上面的代碼不工作。它總是阻止表單提交。 – Viral

+0

@病毒:它必須是關於你如何檢查複選框的東西。首先,'input [class =「linebox」]'是一個非常脆弱的選擇器,如果因爲任何原因向複選框添加第二個類,它將會失敗。你用'linebox'類查找元素的常用方法是input.linebox。您需要使用內置於瀏覽器中的調試器來瀏覽代碼,以瞭解爲什麼'ischk'始終爲'0'。 –