Skip to content

Instantly share code, notes, and snippets.

@snreid
Last active September 11, 2023 17:30
Show Gist options
  • Save snreid/5246361885acf7b42106 to your computer and use it in GitHub Desktop.
Save snreid/5246361885acf7b42106 to your computer and use it in GitHub Desktop.
Jquery DataTables Custom Search Box

I ran into an issue recently where I restyled a page with a searchable table and broke the plugin it was using. I replaced the plugin for Jquery DataTables, but I wanted the page to look the same, so I didn't want to use the built-in search box that DataTables comes with.

After a lot of digging around I found my solution.

##The Javascript

$(document).ready(function(){
var table = $('#person_listing').DataTable();
   //DataTable custom search field
    $('#custom-filter').keyup( function() {
      table.search( this.value ).draw();
    } );
});

##The HTML

....
<!-- This is the custom search box -->
<input id="custom-filter" class="form-control" placeholder="Search...." type="text"/>
...

<!-- This is the datatable. Just like the one you would make out of the box. -->
<table class="table" id="person_listing"> 
   ...
</table>

##The CSS You'll want to hide the default search stuff that comes with datatables.

I didn't need any of the filtering it came with, so I added this to my CSS:

.dataTables_filter { visibility: hidden;}

If you need some of the filtering stuff (like pagination or amount per result drop down) than you can use the exact search box input's ID instead of the higher level "dataTables_filter" class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment