Jquery select / unselect works the first time, not subsequent clicks

$('#parent1').click(function () {
    if ($('#parent1').is(':checked')) {
        $('input[type="checkbox"]').attr('checked', true);
    } else {
        $('input[type="checkbox"]').attr('checked', false);
    }
});

      

This function works, but only the first time, even if it is not part of document.ready (function).

Doesn't it work for subsequent clicks? Is there something missing here? Any help would be much appreciated.

All my child checkboxes are parent2,3,4, ... 15.

<c:forEach var="parent1" items="${model.list}"> 
    <form:checkbox path="list" value="${parent1.name}" label="${parent1.name}" /> 
</for:each>

      

+3


source to share


1 answer


Try using .prop()

instead .attr()

, the behavior is inconsistent. .attr()

$('#parent1').change(function () {
    $('input[type="checkbox"]').prop('checked', this.checked);
});

      



Demo script

+3


source







All Articles