Tuesday, May 15, 2012

Fancy tables in few steps - jQuery DataTables

Dealing with tables... You probably did it thousands of times... Sorting, filtering, pagination...
What do you use? Is there something nice and easy to spare our time and effort?
Here's one proposition, and if you have something better please let me know.

jQuery DataTables! Let's see... First you need to download couple of things:

1) DataTables jQuery plugin - obtaining functionality and basic look and feel
2) jQuery UI - to make it smooth

Instead of a plain table you can have something like this by adding only a few lines of code.
Source code can be downloaded from here.

1) Include needed js and css files (you can find an example below) in the header section.
2) Add the following piece of code:

$(document).ready(function() {
        "bJQueryUI": true,
        "sPaginationType": "full_numbers"
} );

This tells browser that after document is fully loaded it should take table with "people" id and execute dataTable function, and thereby generate fancy table you saw above. Arguments bJQueryUI and sPaginationType tell that support for ThemeRoller should be enabled and that pagination should be presented by full numbers instead of two arrows ("two_button" is a default value), respectively. Beside two given options there are others which you may find just as useful.

IMPORTANT: You need to use VALID table format if you want it to be properly rendered. If <thead>, <th>, and <tbody> tags are missing you'll get a weird result.


  <title>DataTables Demo</title>
  <style title="currentStyle" type="text/css">
   @import "media/css/demo_page.css";
   @import "media/css/demo_table_jui.css";
   @import "media/css/redmond/jquery-ui.custom.css";  
  <script src="media/js/jquery.js" type="text/javascript"></script>
  <script src="media/js/jquery.dataTables.min.js" type="text/javascript"></script>
  <script src="media/js/jquery-ui.lightness.min.js" type="text/javascript"></script>
  <script charset="utf-8" type="text/javascript">
   $(document).ready( function () {
       "bJQueryUI": true,
       "sPaginationType": "full_numbers"     
     } );
   } );
  <table class="display" id="people">
     <th>First Name</th>
     <th>Last Name</th>
<tr><td>Leonardo</td><td>Da Vinci</td><td>Art</td></tr>
<tr><td>Vincent</td><td>Van Gogh</td><td>Art</td></tr>
Note: class "display" is needed for adequate styling.

1 comment: