jQuery Grid: Show/Hide Columns

Show and hide Grid columns.

A live JavaScript/jQuery example of jqxGrid, the jQWidgets Grid component, with its complete source code below. It is one of 139 jqxGrid demos for jQuery.

jqxGrid API used in this demo

Source code

To run it in your own page, load jqx.base.css, a theme and the library files below from npm (npm install jqwidgets-scripts) or the jsDelivr CDN, then add the markup and the script. jQuery is not required: jqxcore.js provides $. Getting started with jqxGrid shows the setup step by step.

The page loads jqx.base.css, a theme and these library files: jqxcore.js, jqxbuttons.js, jqxscrollbar.js, jqxmenu.js, jqxgrid.js, jqxgrid.selection.js, jqxgrid.columnsresize.js, jqxdata.js, jqxcheckbox.js, jqxlistbox.js.

It also loads helper scripts of this demo site, which are not part of the library: demos.js (getWidth() and other layout helpers).

script.js

$(document).ready(function () {
    var url = "../sampledata/beverages.txt";

    // prepare the data
    var source =
    {
        datatype: "json",
        datafields: [
            { name: 'name' },
            { name: 'type' },
            { name: 'calories', type: 'int' },
            { name: 'totalfat' },
            { name: 'protein' }
        ],
        id: 'id',
        url: url
    };
    var dataAdapter = new $.jqx.dataAdapter(source);

    $("#grid").jqxGrid(
    {
        width: 600,
        source: dataAdapter, 
        ready: function () {
            // callback function which is called by jqxGrid when the widget is initialized and the binding is completed.
        },
        columnsresize: true,
        columns: [
          { text: 'Name', datafield: 'name', width: 100, hidden: true },
          { text: 'Beverage Type', datafield: 'type' },
          { text: 'Calories', datafield: 'calories' },
          { text: 'Total Fat', datafield: 'totalfat' },
          { text: 'Protein', datafield: 'protein'}
      ]
    });

    var listSource = [{ label: 'Name', value: 'name', checked: false }, { label: 'Beverage Type', value: 'type', checked: true }, { label: 'Calories', value: 'calories', checked: true }, { label: 'Total Fat', value: 'totalfat', checked: true }, { label: 'Protein', value: 'protein', checked: true}];

    $("#jqxlistbox").jqxListBox({ source: listSource, width: 200, height: 200,  checkboxes: true });
    $("#jqxlistbox").on('checkChange', function (event) {
        $("#grid").jqxGrid('beginupdate');
        if (event.args.checked) {
            $("#grid").jqxGrid('showcolumn', event.args.value);
        }
        else {
            $("#grid").jqxGrid('hidecolumn', event.args.value);
        }
        $("#grid").jqxGrid('endupdate');
    });
});

body.html

<div id="grid"></div>
<div style="margin-top: 20px" id="jqxlistbox"></div>

Learn more

More jQuery Grid demos