简体   繁体   中英

I'm trying to check all child check boxes when parent is checked. But this works only once ! When i try it the next time, child doesn't gets checked?

$(document).ready(function (e) {
    $('.links > input').change(function () {
        if ($(this).is(':checked')) {
            $(this).parent().children('.subLinks').children('.subLinkCheck').children().attr('checked', true);
        } else 
          $(this).parent().children('.subLinks').children('.subLinkCheck').children().attr('checked', false);;
    });
});

It works fine the first time. When I uncheck the child checkbox and then click on the parent checkbox, it fails,

This is the HTML content

<ul id="mainLink">
    <li class="links">
        <input type="checkbox" />Interactive Community
        <ul class="subLinks">
            <li class="subLinkCheck">
                <input class="1" type="checkbox" />Usability Testing</li>
            <li class="subLinkCheck">
                <input type="checkbox" />HFI Certification</li>
        </ul>
    </li>
    <li class="links">
        <input type="checkbox" />Heuristic Evaluations
        <ul class="subLinks">
            <li class="subLinkCheck">
                <input type="checkbox" />Usability Testing</li>
            <li class="subLinkCheck">
                <input type="checkbox" />HFI Certification</li>
        </ul>
    </li>
</ul>

Use .prop() instead of .attr() .

Demo: http://jsfiddle.net/Jrrnj/

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