Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables server side search on enter

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;
    });
});
like image 852
azza idz Avatar asked Oct 18 '25 13:10

azza idz


1 Answers

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 ...

});
like image 142
Gyrocode.com Avatar answered Oct 21 '25 05:10

Gyrocode.com