Group checkboxes in JSFiddle : Part 1 [closed]

2019-09-21 23:46发布

I am trying to do group checkboxes by selecting selectAll. Please check JSFiddle for code sample

JSFiddle

  <fieldset>
    <!-- these will be affected by check all -->
    <div><input type="checkbox" ID="checkall1" onclick="CheckAllClick('checkall1');"> Check all</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
    <!-- these won't be affected by check all; different field set -->
    <div><input type="checkbox" ID="checkall2" onclick="CheckAllClick('checkall2');"> Check all</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>


   function CheckAllClick(id){
    alert(id);
     $(id).closest('fieldset').find(':checkbox').prop('checked', this.checked);

}

Part 2: Continue

3条回答
在下西门庆
2楼-- · 2019-09-22 00:16
function CheckAllClick(id){
    alert(id);
    $(id).closest('fieldset').find(':checkbox').prop('checked', 'checked');
}

The simplest solution is just to changed the checked property to checked seeing as you only selecting inputs you want already

And pass this into your onclick

<div><input type="checkbox" ID="checkall2" onclick="CheckAllClick(this);"> Check all</div>
查看更多
Root(大扎)
3楼-- · 2019-09-22 00:19

What you probably want is this.

$('[id^=checkall]').click(function(){
    $(this).closest('fieldset').find(':checkbox').not(this).prop('checked', function(i,oldval){
       return !oldval; 
    });
});

Fiddle

查看更多
Explosion°爆炸
4楼-- · 2019-09-22 00:36

You have some issues in your function: Try this way:

Js

   function CheckAllClick(elem) {
       $(elem).closest('fieldset').find(':checkbox').prop('checked', elem.checked);
   }

Markup

 <input type="checkbox" ID="checkall1" onclick="CheckAllClick(this);">Check all</div>

Fiddle

Pass the element in the onclick function as this and access it in your code.

If you can go with jquery approach then:

Add a class to your checkall check boxes

 <input type="checkbox" class="checkAll" ID="checkall1" >Check all

With the same code, if you want to make the label click to check the checkbox then just wrap them in label tag, same thing you can do with all the checkboxes by wrapping them in label which generally is a standard way:

 <label><input type="checkbox" class="checkAll" ID="checkall1" >Check all<label>

Bind an event handler to a class

$('.checkAll').on('change', function(){
    $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
})

Fiddle

查看更多
登录 后发表回答