https://mottie.github.io/tablesorter/docs/example-widget-filter-custom.html gives a few examples - First Name column filters by cell content being the filter options, while City and Total have predefined options as filter values.
Sometimes, we need to use the cell contents as filter options because we don't know all the possibilities to use the predefined options, but these cell contents might contain multiple values. Imagine a column Category which lists one or more categories the row is associated to. They could be separated by a comma, new line, br tag, etc. How can we add a dropdown filter at the top listing each separate category without having to list them all? If we use the automatic dropdown, we get the cell contents as filter options: e.g. "Loan, Insurance" will be the filter option rather than two options - "Loan" and "Insurance". If these are separated by break tags, things start to look even uglier.
Thanks!
It sounds like you can use the filter_selectSource
option to add options to the select in that column.
You can use the built-in getOptions
function to obtain the current column values. If they are comma-separated, then you can join the array using commas and re-split the result (demo)
$(function() {
$('table').tablesorter({
theme: 'blue',
widgets: ['zebra', 'filter'],
widgetOptions: {
filter_selectSource: function(table, column, onlyAvail) {
var array = $.tablesorter.filter.getOptions(table, column, onlyAvail);
return array.join(',').split(/\s*,\s*/);
}
}
});
});
Edit: Also make sure to add a "filter-match" class ("filter-select" too) to only match the selected option. It defaults to exact matches otherwise.
Update: If the data is separated using <br>
's then you'll need to add a custom parser to replace the <br>
with a comma, then you can use the same code (demo)
The header will require two more classes to set the parser and tell the filter widget to only use parsed data:
<th class="filter-select filter-match sorter-html filter-parsed">Animals</th>
JS
$(function() {
$.tablesorter.addParser({
id: 'html',
is: function() {
return false;
},
format: function(str, table, cell) {
var c = table.config,
html = cell.innerHTML;
if (html) {
// replace <br> with a comma
html = html.replace(/\s*<br\s*\/?>\s*/g, ',')
html = $.trim(c.ignoreCase ? html.toLocaleLowerCase() : html);
html = c.sortLocaleCompare ? $.tablesorter.replaceAccents(html) : html;
}
return html;
},
type: 'text'
});
$('table').tablesorter({
theme: 'blue',
widgets: ['zebra', 'filter'],
widgetOptions: {
filter_selectSource: function(table, column, onlyAvail) {
var array = $.tablesorter.filter.getOptions(table, column, onlyAvail);
return array.join(',').split(/\s*,\s*/);
}
}
});
});