选中一个框后,选中其他复选框

Ben*_*nny 5 html checkbox jquery

我的页面中有一个复选框.检查时,应检查其他复选框.当我取消选中它时,所有其他复选框也应该取消选中.我怎么能用jQuery做到这一点?或者简单的HTML就足够了?小提琴

    <div>Select All<input type="checkbox" checked="true"></div> 
    1.<input type="checkbox"> 
    2.<input type="checkbox"> 
    3.<input type="checkbox"> 
    4.<input type="checkbox"> 
    5.<input type="checkbox"> 
Run Code Online (Sandbox Code Playgroud)

Pra*_*een 6

Usig jQuery你可以这样做

HTML:

<input id='selectall' type="checkbox" checked="true">
Run Code Online (Sandbox Code Playgroud)

JS:

$('#selectall').change(function () {
    if ($(this).prop('checked')) {
        $('input').prop('checked', true);
    } else {
        $('input').prop('checked', false);
    }
});
$('#selectall').trigger('change');
Run Code Online (Sandbox Code Playgroud)

小提琴检查


Roh*_*mar 5

尝试这个,

<div>Select All<input type="checkbox" id="parent" /></div> 
  1.<input type="checkbox" class="child"> 
  2.<input type="checkbox" class="child"> 
  3.<input type="checkbox" class="child"> 
  4.<input type="checkbox" class="child"> 
  5.<input type="checkbox" class="child"> 

<script>
    $(function(){
      $('#parent').on('change',function(){
         $('.child').prop('checked',$(this).prop('checked'));
      });
      $('.child').on('change',function(){
         $('#parent').prop('checked',$('.child:checked').length ? true: false);
      });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

小提琴

你可以像,

<div>Select All<input type="checkbox" id="parent" /></div> 
  1.<input type="checkbox" class="child"> 
  2.<input type="checkbox" class="child"> 
  3.<input type="checkbox" class="child"> 
  4.<input type="checkbox" class="child"> 
  5.<input type="checkbox" class="child"> 

<script>
    $(function(){
      $('#parent').on('change',function(){
         $('.child').prop('checked',$(this).prop('checked'));
      });
      $('.child').on('change',function(){
         $('#parent').prop('checked',$('.child:checked').length ? true: false);
      });
    });
</script>
Run Code Online (Sandbox Code Playgroud)
$(function() {
  $('#parent').on('change', function() {
    $('.child').prop('checked', this.checked);
  });
  $('.child').on('change', function() {
    $('#parent').prop('checked', $('.child:checked').length===$('.child').length);
  });
});
Run Code Online (Sandbox Code Playgroud)