问题
If you search in data tables a word, it will found anywhere in a word.
Example: Search of "b" in table:
banana
subway
sub
Will return all 3.
How could i set to get only "banana" if i type "b" in search field.
回答1:
I dare to assume you are thinking about jQuery dataTables (have replaced the ambigious datatable tag with the correct jquery-datatables tag too).
You can create a custom filtering function if you want to filter on what the column data begins with, and not search / filter on the entire strings. Like this, which also is case insensitive :
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
//$('#example_filter input') is the default #example filter box
var term = $('#example_filter input')
.val()
.toLowerCase();
for (var i=0;i<data.length;i++) {
value = data[i]
.toString()
.toLowerCase();
if (value.indexOf(term)==0) {
return true;
}
};
return false;
}
);
see demo -> http://jsfiddle.net/v1yguqLz/
Note : This should per the documention and how dataTables worked in "the old days" be a task for a regular expression search, but I cannot get even the simpliest regular expression example to work, neither by table.search()
nor table.column().search()
. Have tried with 1.10.0 through to 1.10.5 (recent version). I guess this has something to do with this bugreport -> https://github.com/DataTables/DataTables/issues/341 and backwards compability.
On the other hand, if you just want to filter on what the column data begins with, then a custom filtering function is the perfect solution anyway.
回答2:
I have a separate search field for one of the columns and here's my solution for begins-with search:
vm.searchForLocation = function() {
vm.dtInstance.DataTable.column(2)
.search("^"+vm.locationCode, true, false )
.draw();
}
来源:https://stackoverflow.com/questions/29359594/jquery-datatables-search-set-search-filter-to-get-only-matches-that-starts-lik