2013-04-16 19 views
5

我試圖通過單擊表頭中的一個複選框來檢查/取消選中所有複選框。首先點擊添加屬性輸入,其次取消選中。它只工作一次。在Firefox和Chrome上進行測試。 Аttributes不斷變化,但這不會顯示在頁面中。我只在瀏覽器調試器中看到它。檢查並取消選中輸入只能用Jquery工作一次

<table> 
    <thead> 
     <tr> 
      <th><input type="checkbox" /></th> 
      <th>#</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td><input type="checkbox" /></td> 
      <td>1</td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" /></td> 
      <td>2</td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" /></td> 
      <td>3</td> 
     </tr> 
    </tbody> 
</table> 

<script type="text/javascript"> 
$(function() { 
    $('th input[type="checkbox"]').click(function(){ 
     if ($(this).is(':checked')) 
      $('td input[type="checkbox"]').attr('checked', 'checked'); 
     else 
      // $('td input[type="checkbox"]').attr('checked', false); 
      $('td input[type="checkbox"]').removeAttr('checked'); 
    }) 
}); 
</script> 

樣品 http://jsfiddle.net/aJhm9/

回答

14

,而是使用屬性的屬性

$(function() { 
    $('th input[type="checkbox"]').click(function(){ 
     if ($(this).is(':checked')) 
      $('td input[type="checkbox"]').prop('checked', true); 
     else 
      $('td input[type="checkbox"]').prop('checked', false); 
    }) 
}); 

http://jsfiddle.net/aJhm9/2/

+0

它的工作原理!謝謝! – glutaminefree

+0

@АндрейН。別客氣。 – Musa

+0

它的工作原理,謝謝!但attr()每次都工作......爲什麼不現在呢? – brandelizer

3

.attr()僅用於修改元素的默認狀態,而不是它的活的狀態下使用.prop()的改變元素的活狀態。

+0

謝謝。這真的很有用。 – SreenathPG

0

使用prop()代替attr()

$(function() { 
    $('th input[type="checkbox"]').click(function(){ 
    if ($(this).is(':checked')) 
     $('td input[type="checkbox"]').prop('checked', true); 
    else 
     $('td input[type="checkbox"]').prop('checked', false); 
    }) 
}); 

working fiddle

0

爲什麼使用jQuery這樣一個小任務?只需將表格頭部的主複選框的ID設置爲唯一名稱即可。然後將一個特定的類添加到表中的所有其他複選框。然後使用下面的代碼: -

var mainCheckbox = document.getElementById('name_of_ID'); 

if(window.addEventListener) { 
    mainCheckbox.addEventListener('change', togglecheckboxes, false); 
} else { 
    mainCheckbox.attachEvent('onchange', togglecheckboxes); 
} 

function togglecheckboxes(){ 
    var otherCheckboxes = document.getElementsByClassName('name_of_CLASS'); //returns an array 
     for(var i = 0; i < otherCheckboxes.length; i++){ 
      otherCheckboxes[i].checked = mainCheckbox.checked; 
     } 
} 
0
<script> 
    $('#select_all').click(function() { 
    $(this).closest('form').find(':checkbox').prop('checked' , this.checked ? true : false); 
}) 
</script>