简体   繁体   中英

How to select the set of check box value using jquery Dynamic

I have a list of set check box with sub check box . Please review the attached image!

[] Gender
    [] Male
    [] Female
    [] Baby

[] Weight 
    [] 50kg
    [] 100kg
    [] 75kg     

[] Color
    [] Brown
    [] Block
    [] White   

What i need , If we select Gender (Parent check box )then the sub check boxes(Male, Female,Baby) also will be checked, If we uncheck the gender check box also the sub check box also uncheck.

My code for check box is below

 {foreach from= $product_param item=key}
                    <div class="parameters"> 
                        <span class="title"><input type="checkbox" name="product_param[]"  value="{$key->id}" id="product_param_selectall" />&nbsp;&nbsp;{$key->param_name}</span> 
                        {foreach from= $key->child_name item=keys}
                        <span><input type="checkbox" name="product_param_child[]"  value="{$key->id}" id="product_param" class="child_param-{$key->id}"/> &nbsp;&nbsp;{$keys->param_name}</span> 
                        {/foreach}
                    </div>
                {/foreach}

Note : The values are dynamic values and id. [] - represent checkbox here

$(".title").on("click",":checkbox",function(){
if($(this).is(":checked"))
{
$(this).closest(".parameters").find("input[name='product_param_child']").attr("checked","checked");
}else{
$(this).closest(".parameters").find("input[name='product_param_child']").removeAttr("checked");

}

});

reference :checked

:checkbox

attr

removeAttr

Here's a solution. Assuming HTML:

<div>
    <input class="parentCheckBox" type="checkbox">Gender</input><br />
    <input class="childCheckBox" type="checkbox">Male</input><br />
    <input class="childCheckBox" type="checkbox">Female</input><br />
</div>
<div>
    <input class="parentCheckBox" type="checkbox">Weight</input><br />
    <input class="childCheckBox" type="checkbox">50kg</input><br />
    <input class="childCheckBox" type="checkbox">100kg</input><br />
</div>

This would work:

$(function() {
    $('.parentCheckBox').click(function() {
        var parentDiv = $(this).parent();
        var isChecked = $(this).prop('checked');
        $('.childCheckBox', parentDiv).prop('checked', isChecked);
    });
});

See this jsfiddle .

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