Filter (always) on initial table rows by selector value

Filter (always) on initial table rows by selector value

oms02oms02 Posts: 11Questions: 3Answers: 0

Description of problem:

I am trying to filter the rows based on a value selected in a select (which should filter the rows through a data attribute).

$('#roles-select').change(function(){
    var role_id = $(this).val();

    $.fn.dataTable.ext.search.push(
        function(settings,data,dataIndex){
            return $(users_table.row(dataIndex).node()).attr('data-role-id') == role_id;
        }
    );
    users_table.draw();

});

The basic example works fine, but when I try to do a different filtering (choosing another value from the select), the filter is done on the rows that have been already filtered.I would need it to be done on the initial rows of the table.

Any idea how to achieve this please?

Thank you very much in advance.

Answers

  • kthorngrenkthorngren Posts: 20,275Questions: 26Answers: 4,765
    edited June 2021

    I suspect the problem is due to pushing the search plugin each time the event handler executes. If you use the select to search three times then that will be three copies of the plugin that will be pushed onto the search stack. I think each keep its value of role_id. Restructuring your code like this should help:

    var role_id = $('#roles-select').val();
     
    $.fn.dataTable.ext.search.push(
        function(settings,data,dataIndex){
            return $(users_table.row(dataIndex).node()).attr('data-role-id') == role_id;
        }
    );
    
    $('#roles-select').change(function(){
        users_table.draw();
    });
    

    Kevin

  • oms02oms02 Posts: 11Questions: 3Answers: 0

    Thank you very much for your reply Kevin.

    It hasn't really been solved. The problem is that the value of "role_id" will change when the event associated with the select is executed. So, this forces me to have the variable "role_id" inside the event declaration and with that updated value, perform the table filter.

    Maybe I could first collect all the rows (I should show all the rows when I load the page), and then, each time the event is executed, add only the rows that pass the filter.

    I hope I have explained correctly.

  • kthorngrenkthorngren Posts: 20,275Questions: 26Answers: 4,765

    Sorry Line 1 needs to be inside the search plugin function like the:

    $.fn.dataTable.ext.search.push(
        function(settings,data,dataIndex){
            var role_id = $('#roles-select').val();
            return $(users_table.row(dataIndex).node()).attr('data-role-id') == role_id;
        }
    );
    

    Kevin

  • oms02oms02 Posts: 11Questions: 3Answers: 0

    Your help was very usefull. Thanks a lot Kevin.

Sign In or Register to comment.