2014-03-04 106 views
0

在這個主題上有很多問題,但沒有人爲我的問題工作,因爲我不知道如何在我的代碼中應用它們 - 我是jQuery的新手。使用jquery檢查/取消選中所有複選框1.10.2

這是我的HTML頁面:

<div id="one"> 
    <div id="positionable2"> 
     <div id="xyz2"> 
     <table id="tab1"> 
      <tr><td class="header"><input type=checkbox id=cbselectall /></td></tr> 
      <tr><td ><input type=checkbox name=case /></td></tr> 
      <tr><td ><input type=checkbox name=case /></td></tr> 
      <tr><td ><input type=checkbox name=case /></td></tr> 
     </table> 
     </div> 
    </div> 
</div> 

現在我的jQuery看起來像下面的東西:

$(function() { 
    $("#one #positionable2 #xyz2 #tab1 #cbselectall").click(function() { 
     if ($("#one #positionable2 #xyz2 #tab1 #cbselectall").is(':checked')) { 
      $("#one #positionable2 #xyz2 #tab1 input[type=checkbox]").each(function() { 
       //$(this).attr("checked", true); 
       $(this).prop("checked", true); 
      }); 

     } else { 
      $("#one #positionable2 #xyz2 #tab1 input[type=checkbox]").each(function() { 
       //$(this).attr("checked", false); 
       $(this).prop("checked", false); 
      }); 
     } 
    }); 
}); 

請注意,我有其他列在表中,使用複選框列是第一柱。在單擊表格標題中的複選框後,應該選擇數據行中的其他列,反之亦然。不知何故,這是行不通的。

由於我是jQuery的新手,不知何故我無法使它工作。請幫忙。

+2

jsfiddle會有所幫助。 – turnt

+0

什麼問題,你的代碼工作正常。這裏是小提琴:http://jsfiddle.net/RCZZ4/ –

+0

在我的頁面與整個頁面內容,它不工作。當我點擊標題複選框時,其他複選框沒有被選中。 –

回答

1

首先您不需要在每個選擇器中指定等級。

$("#cbselectall").on('click', function() { 

    $(this) 
    .parents('table') // go to the table element 
    .find(':checkbox') /* find all checkboxes (note you might need to specifiy 
          if you have other checkboxes in the table that shouldn't get checked 
         */ 
    .prop('checked', $(this).is(':checked')); /* set the checked value to be the value 
               of the check all checkbox */ 
}) 
+0

這不起作用。在加載第一個表格後,帶有複選框的表格將動態加載。它是否導致問題?請幫忙。 –

+0

感謝您的解決方案。有效。我需要把這個jquery放在ajax調用的回調函數中,在這些函數中動態加載。謝謝。 –

相關問題