Getting Started with DataTables

A colleague came to me today trying to get the DataTables jQuery plugin working on a web page. The instructions on the datatables.net site don’t seem to have a complete out-of-the-box example on how to get the plugin working. So here goes.

  1. Download the plugin from datatables.net.
  2. From within the zip archive you downloaded, navigate to the media folder.
  3. Copy the following files into your project:
    • Copy media/css/jquery.dataTables.css to your project’s css folder
    • Copy all the files from the images folder to your project’s images folder
    • Copy js/jquery.dataTables.min.js to your project’s js folder
  4. In the <head> section of your web page, include the following code:
    <link href="css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/jquery.dataTables.min.js"></script>

    This gives you the basic CSS and javascript required to get DataTables working on your page.

  5. Build an html table on your page. Give it an id (I used “table1” in the code below) Make sure you include a header row using <thead> and wrap the table body in a <tbody>.
    <table id="table1">
    	<thead>
    		<tr>
    			<th>Column 1</th>
    			<th>Column 2</th>
    			<th>Column 3</th>
    			<th>Column 4</th>
    		</tr>
    	</thead>
    	<tbody>
    		<tr>
    			<td>Item 1</td>
    			<td>Description 1</td>
    			<td>Data 1</td>
    			<td>More Data 1</td>
    		</tr>
    		<tr>
    			<td>Item 2</td>
    			<td>Description 2</td>
    			<td>Data 2</td>
    			<td>More Data 2</td>
    		</tr>
    		<tr>
    			<td>Item 3</td>
    			<td>Description 3</td>
    			<td>Data 3</td>
    			<td>More Data 3</td>
    		</tr>
    		<tr>
    			<td>Item 4</td>
    			<td>Description 4</td>
    			<td>Data 4</td>
    			<td>More Data 4</td>
    		</tr>
    		<tr>
    			<td>Item 5</td>
    			<td>Description 5</td>
    			<td>Data 5</td>
    			<td>More Data 5</td>
    		</tr>
    	</tbody>
    </table>
    
  6. Finally, just before the closing <body> tag, include the following code:
    <script type="text/javascript">
    $(document).ready(function () {
    	$('#table1').dataTable();
    });
    </script>
    

    This code references the table by its id (table1) and calls the dataTable method to run on it. Simple.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s