I am using jQuery datatable in my ASP.NET MVC website, now I would like to place this custom search box main jQuery datatable, how can I do that using jQuery?
You can simply create a input textbox and implement search functionality using .search() api of jQuery Datatable.
Suppose search textbox html is as below
<input type="text" id="CustomSearchTextField" />
then you can use the below jquery Datatable code
var oTable = $('#yourTable').DataTable(); //using Capital D, which is mandatory to retrieve "api" datatables' object, latest jquery Datatable
$('#CustomSearchTextField').keyup(function(){
oTable.search($(this).val()).draw() ;
})
.keyup is used, instead of .keypress, so that you don't experience any delay in results.
If you are using datatable with lowercase d, .dataTable() ( this will return a jquery object ) use this:
oTable.fnFilter($(this).val());
Based on your jquery Datatable versions, you can use the above code.
Above answer works as needed, but if you want to enable jQuery datatable custom filter search using Regular Expression, you can use the below code
var oTable = $('#yourTable').DataTable(); // capital "D"
var input = $('#CustomSearchTextField');
input.unbind('keyup search input').bind('keypress', function (e) {
if (e.which == 13) {
var keywords = input.val().split(' '),
filter = '';
for (var i = 0; i < keywords.length; i++) {
filter = (filter !== '') ? filter + '|' + keywords[i] : keywords[i];
}
//true (param 2) turns regex on, false (param 3) turns smart search off
oTable.search(filter, true, false).draw();
}
});
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly