Reputation: 2749
Hi I'm using datatables and I would like to filter my data by an exact word.
My table data looks like below;
+-----+----------+
| num | status |
+-----+----------+
| 1 | Active |
+-----+----------+
| 2 | Inactive |
+-----+----------+
| 3 | Active |
+-----+----------+
Whenever I search for Active
I also see all the Inactive
too. Is there any way to filter this so that either the status column only shows exact words.
My JS is below;
$(document).ready(function() {
var table = $('#items').DataTable( {
select: true,
responsive: true
} );
} );
I've been reading through the API however I can't make much sense of it. Perhaps I need to write some regex?
There's an example (I think) here, however I need to modify it to my needs.
Any help or advice would be appreciated.
Upvotes: 3
Views: 9613
Reputation: 1199
To filter search result with an exact match could be done this way -
table.column(index).search("^" + searchText + "$", true, false).draw();
More info - https://stackoverflow.com/a/19114759/698127
Upvotes: 1
Reputation: 1323
Hope this could help. Adding '\\b'
at both end will let the table search for whole word only.
var regex = '\\b' + searchKey + '\\b';
<yourDataTable>.columns(<columnIndex>).search( regex, true, false).draw();
Upvotes: 0
Reputation: 85558
If think you are better off with a custom filter for this task. unbind
the default handlers and perform a exact match filter each time instead. If you have a table
var table = $('#example').DataTable()
Then use a exact match custom filter this way
$('.dataTables_filter input').unbind().bind('keyup', function() {
var searchTerm = this.value.toLowerCase()
if (!searchTerm) {
table.draw()
return
}
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
for (var i=0;i<data.length;i++) {
if (data[i].toLowerCase() == searchTerm) return true
}
return false
})
table.draw();
$.fn.dataTable.ext.search.pop()
})
here is a demo -> http://jsfiddle.net/hmjnqjbs/1/ try search for tokyo
.
OK. I realize the question not is about "exact words" as in exact match filter, but more a whole word search. We want to see Vaio Q900
when we search on vaio
, but we do not want to see VaioQ900
because Vaio
here not is a whole word. This problem is simply solved by using a regex word boundary \b
:
$('.dataTables_filter input').unbind().bind('keyup', function() {
var searchTerm = this.value.toLowerCase(),
regex = '\\b' + searchTerm + '\\b';
table.rows().search(regex, true, false).draw();
})
OP's fiddle from the comment below updated -> http://jsfiddle.net/hmjnqjbs/3/
Now active
, vaio
and so on works as expected.
Upvotes: 5