Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize search input in jQuery Datatables

I'm trying to initialize a Datatable with a default search value that the user can either replace or refine on. This is with server-side data. I haven't read anything where you can do this in the Datatables documentation.

$('#example_filter label input[type=text]').val('Default Product')

The above sets the value but because there isn't a keypress involved the event handler doesn't pick it up. Is there a method I can chain onto the above that would act like the enter key, or should I write an event handler that looks for changes in the field. I'm pretty new to datatables and a jQuery novice.

like image 928
bikedorkseattle Avatar asked Jun 12 '12 23:06

bikedorkseattle


3 Answers

So the proper way of doing this is using the oSearch parameter.

https://datatables.net/docs/DataTables/1.9.0/DataTable.defaults.oSearch.html

$(document).ready( function() {
  $('#example').dataTable( {
    "oSearch": {"sSearch": "Initial search"}
  } );
} )
like image 87
bikedorkseattle Avatar answered Nov 13 '22 07:11

bikedorkseattle


You can trigger an event manually with .trigger():

$('#example_filter label input[type=text]')
    .val('Default Product')
    .trigger($.Event("keypress", { keyCode: 13 }));

Depending on your code, you may want "keyup" instead.

like image 14
gilly3 Avatar answered Nov 13 '22 08:11

gilly3


The proper way is now:

var table = $( '#mytable' ).DataTable();
table.search( 'initial search value' ).draw();
like image 11
josh123a123 Avatar answered Nov 13 '22 06:11

josh123a123