Search code examples
jquerykeypressdatatables

Datatables - Show only input box on table load


I am currently working on a website which includes using Datatables. After customizing a lot, it looks quite like a regular SERP.

The feature I want to implement: On page load only the input box should be displayed and the data rows should be hidden until a search string is entered.

So it actually should behave like you see it on known Search engines. I didn't find info about on datatables' forum or here.

It tried using jQuery keypress() but it did not worked. I tried hiding the table on keypress, didn't worked at all (just to get started).

$("#inputbox").keypress(function () {
      $("table.display").css("display":"none");
    });

But toggle works fine:

$("#button").click(function () {
      $("table.display").slideToggle();
    });

So the problem is somehow with the input box and the keypress function I guess.

Would be really glad to get some feedback here.


Solution

  • You could hide/show the table according to the fact that there are rows:

    $('table').hide();
    $('#inputbox').keyup(function(e) {
       var numRows = $('table tr').length;
       if(numRows >0){
        $('table').show();
       }else{
         $('table').show();    
       }
    });
    

    in this case is uppose you are filtering the table using datatables filtering engine (which is what you should do instead of filtering the data yourself)