Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CheckAll/UncheckAll checkbox with jQuery

I have made a check-box checkall/uncheckall.

HTML

<div> Using Check all function </div>
<div id="selectCheckBox">
<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4
</div>

main.js

function checkAll(parentId,allClass,checkboxClass,allChecked){
    checkboxAll = $('#'+parentId+' .'+allClass);
    otherCheckBox = $('#'+parentId+' .'+checkboxClass);
    checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
    if(allChecked=='false'){
        if(otherCheckBox.size()==checkedCheckBox.size()){
            checkboxAll.attr('checked',true);
        }else{
            checkboxAll.attr('checked',false);
        }
    }else{
        if(checkboxAll.attr('checked')){
            otherCheckBox.attr('checked',true);
        }else{
            otherCheckBox.attr('checked',false);
        }
    }
}

It works fine. But get bulky when I have whole lot of checkboxes. I want to do same work by using jQuery rather than putting onchange on each checkbox. I tried different sort of things but couldnot work. I tried following one:

$('.check input[type="checkbox"]').change(function(e){
    checkAll('selectCheckBox','all','check','true');
});

to do same work as onchange event but didnot work. Where do I went wrong.

like image 729
Ajay Gopal Shrestha Avatar asked Mar 25 '26 12:03

Ajay Gopal Shrestha


2 Answers

I think you just need this: You do not need to pass all the arguments and have the inline onchange event attached to it. You can simplify your code.

$(function () {
    $('input[type="checkbox"]').change(function (e) {
       if(this.className == 'all')
       {
           $('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
       }
        else
        {
            $('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
        }
    });
});

Demo

like image 151
PSL Avatar answered Mar 27 '26 00:03

PSL


Your selector is wrong:

.check input[type="checkbox"]

Above selects any input of type checkbox that has the ancestor with class .check. It'll match this:

<div class="check">
    <input type="checkbox".../> 
</div>

it should be:

input.check[type="checkbox"]
like image 22
Xeon Avatar answered Mar 27 '26 02:03

Xeon