Search code examples
jquerytablesorter

tablesorter buttons in column headers


In an effort to improve the accessibility of the output of the tablesorter plugin, I've been asked to include a button element in the sortable column headers.

When I include a button, the button does not trigger any sorting actions.

This is also the case when I add "button" to the selectorSort option.

I've modified the tablesorter demo jsfiddle so that the first column header includes a button and that "button" has been added to selectorSort.

tablesorter button jsfiddle

(The presence of a button element should serve as a cue to screenreader users that there is an actionable element in the header, since the header itself is usually not actionable. I understand that the aria-label attribute can provide relevant instructions, but I'm told more is needed and I've been specifically directed to add a button element.)


Solution

  • It's built-in to ignore clicks on form elements within the table header. You can override it by changing an internal regular expression (demo):

    HTML

    <table class="tablesorter">
      <thead>
        <tr>
          <th>AlphaNumeric</th>
          <th>Numeric</th>
          <th>Animals</th>
          <th>Sites</th>
        </tr>
      </thead>
      <tbody>
        <!-- ... -->
      </tbody>
    </table>
    

    Script

    $(function() {
      // default regex = /(input|select|button|textarea)/i;
      // remove "button" from ignored formElements list
      $.tablesorter.regex.formElements = /(input|select|textarea)/i;
    
      $('table').tablesorter({
        theme: 'blue',
        headerTemplate: '<button>{content}</button>{icon}',
        widgets: ['zebra', 'columns'],
        selectorSort: "th, button"
      });
    });