0

I am using the following jquery to achieve check all effect in a php page:-

<script>
$(function(){
    $("#checkall").click(function(){
        if($("#checkall").attr('checked')){
            $(".department").attr('checked', true);
        }else{
            $(".department").attr('checked', false);
        }
    });
});
</script>

<input type="checkbox" id="checkall" name="check_all" />

<input type="checkbox" name="department[]" class="department" value=""  checked = "checked"/>

and the check all and uncheck all effect works fine. However, it doesn't work with the reset button in the form. How shall I modify the jquery? Thanks!

Ham
  • 804
  • 3
  • 15
  • 25

3 Answers3

1

Try this demo : http://jsfiddle.net/JCWaT/

My old reply in here: checkbox check all option

Hope fits the need :)

or for your need http://jsfiddle.net/kJCcP/

code

$('input[name="Company"],input[name="Country"]').click(function(){

          $(this).nextAll('input[name="'+this.name+'Sub"]').prop('checked',this.checked);

});
​

OR

$('#checkall').click(function() {

    $(this).nextAll('.department').prop('checked', this.checked);

});​
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
1

Use .prop instead .attr, see the working demo.

$(function(){
    $("#checkall").click(function(){
        if($(this).prop('checked')){
            $(".department").prop('checked', true);
        }else{
            $(".department").prop('checked', false);
        }
    });
});​

And your code could be even short:

$(function(){
    $("#checkall").click(function(){
        $(".department").prop('checked', $(this).prop('checked'));
    });
});​
xdazz
  • 158,678
  • 38
  • 247
  • 274
1
$("#checkall").click(function(){
    $(".department").prop('checked', $(this).is(':checked') ); 
});

The jQuery .prop() docs has a section describing why this should be used instead of manipulating the attribute.

nbrooks
  • 18,126
  • 5
  • 54
  • 66