Add “Show All” option in dropdown filter of datatables

守給你的承諾、 提交于 2021-01-28 21:48:28

问题


I implemented dropdown filter using datatables.

HTML File

<select id='filter'>
    <option value>Show All</option>
    <option value='1'>one</option>
    ...
    <option value='10'>ten</option>
</select>

<table id='table'>
    ...
</table>

Javascript

var table = $("#table").DataTable();

$("#filter").change(function(){
    var filterValue = $(this).selectedOptions[0].label;

    if ( filterValue == '' ){
        // **Show All Functionality**

    } else {
        table.column(2).search(filterValue).draw();
    }
});

If I select one to ten, it works fine, but I want to show all again after filter was applied.
Is there any function to do so?

Thanks.


回答1:


You need to draw the table again, after searching for an empty string (which should return all rows): table.search('').draw();

And if that works, you can get rid of the if clause and just do:

$("#filter").change(function() {
    table.search($(this).val()).draw();
});



回答2:


You just need to make small changes in your code as follows:

<option value='0'>Show All</option>  // Set value as 0 for "Show All" option   

 var table = $("#table").DataTable();

 $("#filter").change(function(){
       var filterValue = $(this).val();

       if ( filterValue == '0' ){  // Check for show all option
            table.search(filterValue).draw(); 

       } else {
            table.search(filterValue).draw();
       }
    });


来源:https://stackoverflow.com/questions/36819915/add-show-all-option-in-dropdown-filter-of-datatables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!