Search code examples
jquerytablesorter

Sort Multiple Fields with jQuery Tablesorter Using Select Field


I'm using Mottie's fork of Tablesorter: https://github.com/Mottie/tablesorter

What I want to do, is Filter or Sort a table using multiple select fields outside of the actual table. So I don't want to use the filters that appear under the table heading.

I've found a few options that work one by one. Such as adding these two to my tablesorter script:

 jQuery(".selectParty").bind('change', function (e) {
     var cols=[]
     cols[2] = $(this).val()
    jQuery('table').trigger('search', [cols]);
 })


 jQuery(".selectState").bind('change', function (e) {
     var cols=[]
     cols[0] = $(this).val()
    jQuery('table').trigger('search', [cols]);
 })

And here are HTML select fields which are above the table:

     <select class="selectState tablesorter-filter" data-column="0">
     <option class="reset" value="">No Filter</option>
     <option>Illinois</option>
     <option>Indiana</option>
     </select>    

     <select class="selectParty tablesorter-filter" data-column="2">
     <option class="reset" value="">No Filter</option>
     <option>Democratic</option>
     <option>Republican</option>
     </select>

       <table class="tablesorter"><thead><tr><th data-placeholder="Search" class="filter-match">State</th><th data-placeholder="Search" class="filter-match">Name</th><th data-placeholder="Search" class="filter-match">Party</th></tr></thead><tbody>

These work fine on their own, but let's say I select Sort by Illinois first, it sorts the table by Illinois. But then I go ahead and sort by Democractic, it resets the State filter to show all rows with Democratic.

Is it currently possible to have tablesorter let you filter by multiple fields outside of the table itself? I've seen examples where you can sort by multiple columns by holding Shift, but that doesn't work on tablets...any help is greatly appreciated!


Solution

  • Instead of clearing out the col variable, you can just modify the filter for a specific column, like this:

    var cols = [];
    
    jQuery(".selectParty").bind('change', function (e) {
        cols[2] = $(this).val();
        jQuery('table').trigger('search', [cols]);
    });
    
    jQuery(".selectState").bind('change', function (e) {
        cols[0] = $(this).val();
        jQuery('table').trigger('search', [cols]);
    });