135

I'm using DataTables (datatables.net) and I would like my search box to be outside of the table (for example in my header div).

Is this possible ?

Anirvan
  • 6,214
  • 5
  • 39
  • 53
Athanasios Emmanouilidis
  • 2,084
  • 3
  • 18
  • 30

12 Answers12

277

You can use the DataTables api to filter the table. So all you need is your own input field with a keyup event that triggers the filter function to DataTables. With css or jquery you can hide/remove the existing search input field. Or maybe DataTables has a setting to remove/not-include it.

Checkout the Datatables API documentation on this.

Example:

HTML

<input type="text" id="myInputTextField">

JS

oTable = $('#myTable').DataTable();   //pay attention to capital D, which is mandatory to retrieve "api" datatables' object, as @Lionel said
$('#myInputTextField').keyup(function(){
      oTable.search($(this).val()).draw() ;
})
mginius
  • 104
  • 2
  • 12
netbrain
  • 9,194
  • 6
  • 42
  • 68
  • 8
    You should definitely use .keyup instead of .keypress, otherwise you'll experience a delay in results – Sævar Sep 11 '13 at 15:38
  • 1
    I messed with putting `$(".dataTables_filter :input").focus().val(value).keypress();` in the `keyup` on my input for about an hour, before finding this. Never though to use the API.. Elegant solution! – MattSizzle May 03 '14 at 23:00
  • 3
    The JS needs to change to use .search( $(this).val() ).draw() in place of fnFilter. See: https://datatables.net/manual/api#Chaining I changed this answer to fix it, but it appears it needs to be peer reviewed first. – Shane Grant Oct 12 '14 at 03:05
  • 17
    Remark: You will still need the "searching: true" option, and then you probably want to hide the default searchbox so just set the sDOM option to null. – bang Oct 23 '14 at 08:10
  • ...or to the correct format of your choice of course :) More info : http://datatables.net/examples/basic_init/dom.html – bang Oct 23 '14 at 08:17
  • 9
    Instantiating $().dataTable() with a small "d" will return a jQuery object rather than a DataTables API instance. The latter can be achieved by calling "oTable = $('#myTable').DataTable();" with a capital "D". This is required to be able to call .search on it (if will throw a "function undefined" error otherwise). See: https://www.datatables.net/faqs/#api – Lionel Mar 30 '15 at 07:28
  • http://stackoverflow.com/questions/40504608/use-search-bar-to-filter-data-in-data-table-based-on-search-string?noredirect=1#comment68443393_40504608 Can anyone have a check on this? – Phoenix Nov 24 '16 at 05:56
  • 1
    And to keep the full search functionality, the search string needs to be displayed after refresh in the custon input. This line do the job for me: `$('#myInputTextField').val(oTable.search());` – Tanya Nov 28 '16 at 12:36
  • @netbrain I have the same problem but your solution doesn't work for me. – Praburaj Feb 11 '17 at 05:55
  • @netbrain My code js file link is here http://pastebin.com/SDe3wCPf. I always get no records when i start typing in my input field. – Praburaj Feb 11 '17 at 05:59
  • @prabu try adding the searching: true option. – netbrain Feb 12 '17 at 06:24
  • Search was not working for me. But when I changed $('#myTable').dataTable(); to $('#myTable').DataTable(); it started working – Kiren S Sep 19 '17 at 12:39
  • Thank you for this answer - saved me some time looking through the docs. For my use with the Angular JS version of this library - you can use an implementation like so: vm.dtInstance.DataTable.search(event.value).draw(); – Nick Taras Mar 14 '18 at 00:30
  • is this applicable for server side? – mending3 May 18 '21 at 05:31
39

As per @lvkz comment :

if you are using datatable with uppercase d .DataTable() ( this will return a Datatable API object ) use this :

 oTable.search($(this).val()).draw() ;

which is @netbrain answer.

if you are using datatable with lowercase d .dataTable() ( this will return a jquery object ) use this :

 oTable.fnFilter($(this).val());
zizoujab
  • 7,603
  • 8
  • 41
  • 72
  • 4
    `oTable.fnFilter($(this).val());` Worked for me too, – shabeer90 Mar 20 '15 at 16:04
  • 10
    Both methods are valid, depending on how are you calling the datatable: ` oTable.search($(this).val()).draw() ;` you use when you call it: `.DataTable()` and this one: `oTable.fnFilter($(this).val());` when you use `.dataTable()` The difference is at the capital D. Hope it helps! – Lvkz Aug 05 '15 at 20:45
  • Gives a "oTable.fnFilter is not a function" error for datatables version 1.10.5 – Ege Bayrak Mar 24 '16 at 12:20
  • Just figured that with jQuery you can also access Database API like this : `oTable.api().search($(this).val()).draw();` It can be useful, especially if you want manual control over pagination `length` as well : `oTable.api().page.len($(this).val()).draw();` – Ghis May 19 '18 at 22:06
16

You can use the sDom option for this.

Default with search input in its own div:

sDom: '<"search-box"r>lftip'

If you use jQuery UI (bjQueryUI set to true):

sDom: '<"search-box"r><"H"lf>t<"F"ip>'

The above will put the search/filtering input element into it's own div with a class named search-box that is outside of the actual table.

Even though it uses its special shorthand syntax it can actually take any HTML you throw at it.

mekwall
  • 28,614
  • 6
  • 75
  • 77
  • 1
    @Marcus: actually I feel that sDom is not quite elegant to use, put aside the fact that we can't fully customize the search box (there's a hardcode "Search" text in that box). – Hoàng Long Jan 23 '13 at 10:26
  • 1
    but its still inside div.datatables_Wrapper, any way to move it outside of it as well ? – Artur79 Apr 15 '13 at 14:53
  • @Artur79 Sadly no. Not without hacking the source of Datatables, at least. – mekwall Apr 15 '13 at 14:59
  • 3
    <333 this syntax `'<"search-box"r><"H"lf>t<"F"ip>'` not sure if something worse exists – Cristian E. Jun 18 '15 at 14:43
  • @HoàngLong you actually can customise the search box using options like this: `language: { search: "example", searchPlaceholder: "example" }` – Flimm Sep 14 '17 at 13:31
13

For recent and new version of DataTables, You should follow these steps:

1- searching option must be true.

2- Hide default search input:

.dataTables_filter {
    display: none;
}

3- Add new search input:

<input type="text" id="search">

4- Request search:

$('#search').keyup(function() {
    var table = $('.table-meetups').DataTable();
    table.search($(this).val()).draw();
});
Tomas Votruba
  • 23,240
  • 9
  • 79
  • 115
Abolfazl Mohajeri
  • 1,734
  • 2
  • 14
  • 26
10

This one helped me for DataTables Version 1.10.4, because its new API

var oTable = $('#myTable').DataTable();    
$('#myInputTextField').keyup(function(){
   oTable.search( $(this).val() ).draw();
})
cinnamonbear
  • 101
  • 1
  • 2
  • Note the capital "D" of "var oTable = $('#myTable').DataTable();" (https://www.datatables.net/faqs/#api) – Lionel Mar 30 '15 at 07:30
8

I had the same problem.

I tried all alternatives posted, but no work, I used a way that is not right but it worked perfectly.

Example search input

<input id="searchInput" type="text"> 

the jquery code

$('#listingData').dataTable({
  responsive: true,
  "bFilter": true // show search input
});
$("#listingData_filter").addClass("hidden"); // hidden search input

$("#searchInput").on("input", function (e) {
   e.preventDefault();
   $('#listingData').DataTable().search($(this).val()).draw();
});
Bruno Ribeiro
  • 1,280
  • 16
  • 21
  • Thanks for the hint of hiding search input and "input" event. But mind you, you are instantiating another DataTable inside .on("input". – Sravan Feb 04 '21 at 21:11
7

More recent versions have a different syntax:

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Note that this example uses the variable table assigned when datatables is first initialised. If you don't have this variable available, simply use:

var table = $('#example').dataTable().api();

// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
    table.search(this.value).draw();
});

Since: DataTables 1.10

– Source: https://datatables.net/reference/api/search()

Jonny
  • 2,223
  • 23
  • 30
5

I want to add one more thing to the @netbrain's answer relevant in case you use server-side processing (see serverSide option).

Query throttling performed by default by datatables (see searchDelay option) does not apply to the .search() API call. You can get it back by using $.fn.dataTable.util.throttle() in the following way:

var table = $('#myTable').DataTable();
var search = $.fn.dataTable.util.throttle(
    function(val) {
        table.search(val).draw();
    },
    400  // Search delay in ms
);

$('#mySearchBox').keyup(function() {
    search(this.value);
});
Community
  • 1
  • 1
citxx
  • 2,525
  • 17
  • 40
4

This should be work for you:(DataTables 1.10.7)

oTable = $('#myTable').dataTable();

$('#myInputTextField').on('keyup change', function(){
  oTable.api().search($(this).val()).draw();
})

or

oTable = $('#myTable').DataTable();

$('#myInputTextField').on('keyup change', function(){
  oTable.search($(this).val()).draw();
})
Sky Yip
  • 1,059
  • 12
  • 10
1

You could move the div when the table is drawn using the fnDrawCallback function.

    $("#myTable").dataTable({
    "fnDrawCallback": function (oSettings) {
        $(".dataTables_filter").each(function () {
            $(this).appendTo($(this).parent().siblings(".panel-body"));
        });
    }
});
ebrown
  • 811
  • 1
  • 8
  • 13
  • Or if you use a newer version of datatable you will have: `"drawCallback": function (settings) { $(".dataTables_filter").each(function () { $(this).appendTo($(this).parent().siblings(".panel-body")); }); },` – Daniel Dudas Oct 20 '15 at 20:52
1
$('#example').DataTable({
   "bProcessing": true,
   "bServerSide": true,
   "sAjaxSource": "../admin/ajax/loadtransajax.php",
   "fnServerParams": function (aoData) {
        // Initialize your variables here
        // I have assign the textbox value for "text_min_val"
        var min_val = $("#min").val();  //push to the aoData
        aoData.push({name: "text_min_val", value:min_val});
   },
   "fnCreatedRow": function (nRow, aData, iDataIndex) {
       $(nRow).attr('id', 'tr_' + aData[0]);
       $(nRow).attr('name', 'tr_' + aData[0]);
       $(nRow).attr('min', 'tr_' + aData[0]); 
       $(nRow).attr('max', 'tr_' + aData[0]); 
   }
});

In loadtransajax.php you may receive the get value:

if ($_GET['text_min_val']){
    $sWhere = "WHERE ("; 
    $sWhere .= " t_group_no LIKE '%" . mysql_real_escape_string($_GET['text_min_val']) . "%' ";
    $sWhere .= ')';
}
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Senanayaka
  • 309
  • 6
  • 18
0

If you are using JQuery dataTable so you need to just add "bFilter":true. This will display default search box outside table and its works dynamically..as per expected

$("#archivedAssignments").dataTable({
                "sPaginationType": "full_numbers",
                "bFilter":true,
                "sPageFirst": false,
                "sPageLast": false,
                "oLanguage": {
                "oPaginate": {
                    "sPrevious": "<< previous",
                    "sNext" : "Next >>",
                    "sFirst": "<<",
                    "sLast": ">>"
                    }
                },
            "bJQueryUI": false,
            "bLengthChange": false,
            "bInfo":false,
            "bSortable":true
        });    
Nikhil Thombare
  • 1,058
  • 2
  • 11
  • 26
  • The question was to change the position of the dynamically created . Putting it OUTSIDE the table – M.C. Jan 25 '16 at 09:25