2013-04-16 5 views
5

すべてのチェックボックスをチェックしたり、チェックを外したりしようとしています。最初に、属性を入力に追加するをクリックし、2番目のチェックを外します。それは一度だけ動作します。 FirefoxとChromeでのテスト。 Аribributesは変更を続けますが、ページには表示されません。私はブラウザのデバッガでしか見ません。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> 
関連する問題