简体   繁体   中英

Toggle checkbox - click on parent DIV element

I have few div elements and inside every div one checkbox. On click this div I want to check/uncheck checkbox and add class like active or checked. Have some code if you have any idea.

<div class="filter">
    <div id="select_10">
       <input type="checkbox" name="what" />
       visible1
    </div>
    <div id="select_91">
       <input type="checkbox" name="ever" />
       visible2
    </div>
    <div id="select_101">
       <input type="checkbox" name="whatever" />
       visible3
    </div>    
</div>

using this code:

$(document).on("click", "div.filter div", function (event) {
    var target = $(event.target);
    var id = $(this)attr('id');
    if (target.is('div#'+id+' input:checkbox')) {
        return;
    }
    var checkbox = $(this).find("input[type='checkbox']");
    checkbox.prop("checked", !checkbox.is(':checked'));
});

$(this)attr('id'); should have a . like in

$(this).attr('id');

That's it.


Why using DIV and JS when we have <label> for that purpose !

 .filter label { cursor: pointer; display: block; background: #eee; margin:5px; padding: 10px; } 
 <div class="filter"> <label id="select_10"> <input type="checkbox" name="what" /> visible1 </label> <label id="select_91"> <input type="checkbox" name="ever" /> visible2 </label > <label id="select_101"> <input type="checkbox" name="whatever" /> visible3 </label > </div> 

all you need. Style label as you would for your DIV by just adding eventually display: block;


Or you can even move the inputs before the label and style the complete LABEL elements in pure CSS:

 .filter input{ position: absolute; visibility: hidden; } .filter label { cursor: pointer; display: block; margin:5px; padding: 10px; background: #eee; } .filter input:checked + label{ background: #cf5; } .filter label:before{content: "\\2610";} .filter input:checked + label:before{content: "\\2611";} 
 <div class="filter"> <input id="ckb_10" type="checkbox" name="what" /> <label for="ckb_10"> what </label> <input id="ckb_91" type="checkbox" name="foo" /> <label for="ckb_91"> foo </label> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM