Search code examples
javascriptjquerycheckboxtablesorter

Tablesorter: External Checkbox to Filter


I'm trying to use an external checkbox to filter the table based on the contents of a column. The only related questions/solutions I've found are dealing with checkboxes inside the table used for sorting purposes.

Desired Functionality: For the sake of simplicity, let's say column 4 contains either a 0 or 1. When this external checkbox is checked, I'd like it to filter the results (where column 4 contains the value 1).

Working Alternative: When using an external select (dropdown), I can achieve the desired functionality. The select element (<select id="test_select" name="test_select" class="search" data-column="4">) has an option (<option value="1">1</option>) and then, inside the "widgetOptions" configuration, have filter_external: '.search'.

But a having a select with one option doesn't make sense as far as usability is concerned.

Any suggestions?


Solution

  • Use the "search" method to perform any queries on the table data.

    Here is an example

    HTML

    <label><input id="findzeroes" type="checkbox"> Find Zeroes</label>
    

    Script

    $(function() {
    
      $('#findzeroes').on('change', function(){
        var query = [];
        if (this.checked) {
          // target 4th column (zero-based index)
          query[3] = '0';
        }
        $('table').trigger('search', [ query ]);
      });
    
      $('table').tablesorter({
        theme: 'blue',
        widgets: ['zebra', 'filter']
      });
    });
    

    Using a <select> instead of a checkbox will also work.