Reputation: 663
I have seen many threads here on SO that show how to implement search on enter (default behavior is search after every keypress) but for some reason when i have server side processing on DataTables code gets ignored and default behavior is back. Anyone has any idea on how to start search only after user pressed enter?
This is what i got now and search part of the code gets plain ignored (also searchDelay has no effect - that's from DataTables documentation)
var adminRoles;
$(document).ready(function () {
adminRoles = $('#adminRoles').dataTable({
info: true,
order: [[0, 'asc']],
processing: true,
serverSide: true,
searchDelay: 500, //does't work
ajax: {
url: "@Url.Action("GetRoles","Admin")",
type: "POST"
},
columnDefs: [
{ data: "Name", targets: 0 },
{ data: "KeyName", targets: 1 },
{
data: "Id",
className: "text-center editDetail clickable",
render: function (data, type, row) {
return '<button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-pencil text-primary" /></button>';
},
sortable: false,
searchable: false,
targets: 2
}
],
language: {
url: '@Url.Content(@Resource.js_DataTables_Language)'
}
}).api();
$('#adminRoles_filter input').unbind().bind('keypress', function (e) {
if (e.which == 13) {
alert('You pressed enter!'); //doesn't get hit
//adminRoles.search(this.value).draw();
}
return;
});
});
Upvotes: 4
Views: 8238
Reputation: 58900
Use initComplete
option to define a function that will be called when the table has been initialized and use the code below to search on Enter key.
adminRoles = $('#adminRoles').dataTable({
initComplete: function(){
var api = this.api();
$('#adminRoles_filter input')
.off('.DT')
.on('keyup.DT', function (e) {
if (e.keyCode == 13) {
api.search(this.value).draw();
}
});
},
// ... skipped ...
});
Upvotes: 9
Reputation: 663
I figured it out. Problem was with language url. When DataTables is rendered it waits for language file to be read completely only then can it be displayed. Bind and unbind actions can't be done because input element is not there. So to counter that i've added it on fnInitComplete as someone suggested it on DataTables forums. You will also need fnFilterOnReturn.js
jQuery.fn.dataTableExt.oApi.fnFilterOnReturn = function (oSettings) {
var _that = this;
this.each(function (i) {
$.fn.dataTableExt.iApiIndex = i;
var $this = this;
var anControl = $('input', _that.fnSettings().aanFeatures.f);
anControl
.unbind('keyup search input')
.bind('keypress', function (e) {
if (e.which == 13) {
$.fn.dataTableExt.iApiIndex = i;
_that.fnFilter(anControl.val());
}
});
return this;
});
return this;
};
Code:
...
order: [[0, 'asc']],
processing: true,
serverSide: true,
"fnInitComplete": function (oSettings, json) {
adminRoles.fnFilterOnReturn();
},
ajax: ...
Upvotes: 0