nysmoon
nysmoon

Reputation: 37

Bootstrap Table Filter by Multiple Columns

I am using Bootstrap Table by wenzhixin. I need to filter by several columns. For example, I need to filter Countries and then Cities.

I have two select fields for each field in the table (Select Country and Select City).

The way I am doing it right now is I apply filterBy method on change of select option:

    $('#countries-list').on('change', function (evt) {
        var selectedCountry = $('#countries-list').select2('val');
        if (selectedCountry == "all") {
            $tableFilter.bootstrapTable('filterBy');
        } else {
            $tableFilter.bootstrapTable('filterBy', {country: selectedCountry});                
        }
    });

    $('#cities-list').on('change', function (evt) {
        var selectedCity = $('#cities-list').select2('val');
        if (selectedCity == "all") {
            $tableFilter.bootstrapTable('filterBy');
        } else {
            $tableFilter.bootstrapTable('filterBy', {city: selectedCity});              
        }
    });

The problem is that they overwrite each other. I would appreciate any suggestions on how to apply second filter only to the results of the first one, not to the entire dataset.

Thank you!

Upvotes: 2

Views: 22752

Answers (2)

Pablo Tirado
Pablo Tirado

Reputation: 81

I suggest that you use the bootstrap-table extension Filter-Control.

Upvotes: 5

Mille
Mille

Reputation: 48

Fairly old question but I just struggled with the same thing today and just figured out a solution.

Set needed variables:

var $table = $('#table-id')
var FilterOptions = {}

Create a function to check if a object is empty:

function isEmpty(obj) {
        for(var key in obj) {
            if(obj.hasOwnProperty(key))
                return false;
        }
        return true;
    }

Create a function that will filter the table with the help of our isEmpty() function:

function FilterTable(){
        if(isEmpty(FilterOptions)){
            $table.bootstrapTable('filterBy', {})
        } else {
            $table.bootstrapTable('filterBy', FilterOptions)
        }
    }

Then for each of our select fields we will create a function that adds/change a property to our FilterOptions object depending on what is selected or deletes the property if the default option is selected ("all" in this example). At the end we filter our table with our FilterTable() function.

$('#Selector_column1_filter').change(function(){
        if ($(this).val() != "all") {
            FilterOptions.column1 = $(this).val();
        } else {
            delete FilterOptions.column1;
        }
        FilterTable();
    })

Upvotes: 0

Related Questions