How to implement a sortable and filterable dataTable

August 30, 2012

The scenario is this: You have a table and you want to let users sort each column and filter the results. Fortunately, jQuery and dataTables has just what you need. There are so many options out there which can help you accomplish anything from a simple implementation to a full-fledged server-side sorting on the scale of Amazon.com. (Amazon is the most prominent website to feature the dataTable functionality.)

There are 7 easy steps to making the table happen.

  1. Create a table with a table head <thead>, body <tbody>, and foot <tfoot>. Don’t forget to give your data Table a class name.
  2. If you wish to filter each individual column with a search box, create a <tr><th><input> inside of the <tfoot>.
  3. Include jquery.js, jquery.dataTables.js, and the jquery.dataTables.columnFilter.js files.
  4. If you wish to use the formatting to go along with your tables, include the @import CSS segment:
  5. <style type="text/css" title="currentStyle">
    			@import "/js/DataTables/media/css/demo_page.css"; 
    			@import "/js/DataTables/media/css/header.ccss";
    			@import "/js/DataTables/media/css/demo_table.css";
    </stule>
  6. Make your $document ready and include the code:
  7. <script>
    $(document).ready(function(){
    $('.dataTable').dataTable()
    .columnFilter();
    });
    </script>
  8. If you wish to skip columns with the filter function, you can add this:
  9. $(document).ready(function() {
    	$('.dataTable').dataTable()
    	
    	.columnFilter({
    		aoColumns: [
    			null,
    			{type: "text"},
    			{type: "text"},
    			{type: "text"}		]
    	});
    });
  10. And if you only want to sort, just eliminate the .columnFilter function like this:
<script>
$(document).ready(function(){
$('.dataTable').dataTable();
});
</script>

It’s really quite easy to use. You can then select individual elements and style them to your heart’s content.

And when you’re ready, you can look at more advanced examples here:

Author

Stay in Touch!

Stay in Touch!
Solutions Architecture

browse through our blog articles

Blog Archive