santa
santa

Reputation: 12512

check/uncheck w/jQuery

I have the following function that checks/unchecks all checkboxes on the page by selecting one

$("#checkall").click(function() {
    var checked_status = this.checked;
    $("input:checkbox").each(function() {
        this.checked = checked_status;
    });
});

I need to modify it in such a way that if all are selected by clicking checkall and then one is unchecked the #checkall gets unchecked as well. Or do I need to create a separate function for this?

Also when NONE of the checkboxes is selected I need to add a class to another element.

$("#myElement").addClass("disabled");

Putting it all together sort of complicates things for me.

Upvotes: 1

Views: 235

Answers (4)

voigtan
voigtan

Reputation: 9031

I would use change event.

Is this what you are after?:

<div class="checkall">
    <input type="checkbox" id="checkall">
</div>
<div id="list">
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
</div>

and jquery:

var checkboxes = $(":checkbox", "#list").change(function() {
        var allIsChecked = checkboxes.length === checkboxes.filter(":checked").length;

        checkAll[0].checked = allIsChecked;
});

var checkAll = $("#checkall").change(function() {
        checkboxes.prop("checked",this.checked);
});

demo (if you are using jquery 1.6+): http://jsbin.com/ezofal/edit

added the #MyElement class toggle in this link: http://jsbin.com/ezofal/2/edit

Upvotes: 3

Joseph Marikle
Joseph Marikle

Reputation: 78520

$("input:checkbox").click(function() {
    var checked_status = this.checked;
    if($(this).is("#checkall")) {
        $("input:checkbox").each(function() {
            this.checked = checked_status;
        });
    } else {
        $("#checkall").attr('checked', ($("input:checkbox:not(#checkall):checked").length ==
                                        $("input:checkbox:not(#checkall)").length));
    }
});

http://jsfiddle.net/N2dH5/1/

tested

Some ideas stolen from @Toukakoukan

Upvotes: 1

Sam Martin
Sam Martin

Reputation: 1248

$(document).ready(function(){
    $("#checkall").click(function() {
        var checked_status = this.checked;
        $("input:checkbox").each(function() {
            this.checked = checked_status;
        });
    });
    $('input[type=checkbox]:not(#checkall)').change(function(){
        if($('input[type=checkbox]').length !=  $('input[type=checkbox]:checked').length){
              $('#checkall').attr('checked', false);
        }
    });
});

jsFiddleDemo

Upvotes: 2

Chris G.
Chris G.

Reputation: 3981

var checked_status = false;
$("#checkall").click(function() {
checked_status = this.checked;
$("input:checkbox").each(function() {
    this.checked = checked_status;
});
});
$("input:checkbox").click(function(){
   if(checked_status == true) {
       $('#checkall').checked = false;
   }
});

Upvotes: 1

Related Questions