简体   繁体   中英

Show and hide column in a table using drop down

I have a table, which looks exactly like this one: https://www.datatables.net/examples/api/show_hide.html

I now want to replace the headers ( the th things ) with a drop down. I want to hide and show columns thanks to those drop downs (they can click and show what they want).

I was also wondering if I can leave some columns by default. Is all of that possible ?

This is definitely possible, but have you started developing anything? Do you have any code for us to work with? I can point you at a couple good sources to get you started if not.

First off, here is how to add a select menu to a column:

<th>Date
    <select id="filter_dt" class="headerFilter">
        <option value="show">Show</option>
        <option value="hide">Hide</option>
    </select>
</th>

The above code will provide a drop down for columns.

You could show/hide columns by doing the following (from DOCs ):

$('.headerFilter').on('click', function(e) {
    e.preventDefault();

    // Get the column API object
    var column = table.column($(this).attr('data-column'));

    // Toggle the visibility
    column.visible(! column.visible());
});

As far as a default column, it depends on how you're rendering the data in the table, but you should be able to accomplish this by simply doing the following (Directly from the DOCs ):

$('#example').DataTable( {
    ajax: "../php/staff.php",
    columns: [
        { data: "first_name" },
        { data: "last_name" },
        { data: "position" },
        { data: "office" },
        { data: "start_date" },
        { data: "salary", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) },
        {
            data: null,
            defaultContent: '<a href="#" class="remove">Delete</a>',
            orderable: false
        },
    ]
});

The last column specified in the <a href="#" class="remove">Delete</a> value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM