Monday, April 18, 2011

check/uncheck all records using jQuery

How Do I? check/uncheck all checkboxed on header check box click using jQuery


Working with tables using javascript became easy with jQuery or even with any sort of DOM manipulation. There is one task we repeatedly do i.e. to check/uncheck all the records. Even though its not a difficult problem and usually everybody has its own implementation of this activity. There is perhaps a generic code written which is used by all.

Small challenge:
There is one complexity with this scenario. If all checkbox are selected, then header checkbox should be checked. So in any case if a user uncheck any of record checkbox, it should uncheck the header checkbox also and vice versa if user manually select all records then header checkbox should be checked
The following code is written to overcome such situation in minimum line of codes. Please see the comments and implementation and let me know if you like this approach.

//call the function when document is ready to bind the events with header checkbox to select/unselect all
$(function(){
    //call the function on document ready function
    SelectAll("tblTest","cbHeader");
});

function SelectAll(tableID,cbHeaderID)
{
    //select the table that has the checkboxes
    var table=$("table[id$='"+tableID+"']");
    //bind event with header checkbox change event
    $("input[id$='"+cbHeaderID+"']",table).change(function(){
    //check/uncheck all the checkboxes based on header element status
    $("input:checkbox",table).attr('checked',$(this).attr('checked'));});
    //bind event with all the other checkboxes 
    $("input:checkbox:gt(0)",table).change(
    function(){  
        // if number of checked checkboxes are les than number of checkboxes than uncheck the header checkbox
        var isAllChecked=$("input:checkbox:gt(0)",table).size() > $("input:checkbox:checked:not(#"+cbHeaderID+")",table).size()?false:true;
        $("input:checkbox:first",table).attr('checked',isAllChecked);
    });
    
}

Click here to download the sample page

10 comments: