Monday, April 18, 2011

show hide columns of table in jQuery

How Do I? Show/hide columns of table based on Multi Select list box in jQuery


Large reports with many columns you must give some extra customization. One of them is to show hide columns based on a multi select list. This article describes the easiest way of doing it with a generic code.
Assumption:
Table is well formatted i.e. it has a thead and tbody tag.

Brief Description:
When page load and document ready function is fired, it will bind a function to change event of multiple select list.
It then loop over the whole select options to see the selected items and hide then if they are selected or show them if they are not selected.
Here is the code,

$(function(){
// add an function on multiple select list ddlcolumns change event
    $("#ddlColumns").change(function(){
        //get the table whose columns will be manipulated
        var table=$("#tblTest");
        //get the first row or thead row
        var headerRow=$("tr:first",table);
        // loop over each option in multiple select list
        $("option",this).each(function(){
            //get the index of current option value e.g. "Header 1"
            var index=$("th:contains("+this.value+")").index();
            // if current option is selected then hide the column along with header else show the column if it is already hidden
            if($(this).attr('selected'))
            {
                $("td:nth-child("+(index+1)+"),th:nth-child("+(index+1)+")",table).hide();
            }
            else
            {
                $("td:nth-child("+(index+1)+"),th:nth-child("+(index+1)+")",table).show();
            }
        });
    });
});

I hope this will help.
Click here to Download sample

1 comment: