<< Back to Main Work Page

Introduction to DataTables

You can find DataTables and a lot of other useful things for datatables at the website: http://datatables.net/

I found it while looking for a plugin that could sort columns in an HTML table. As noted on my main work page, I like it for the instant search. Another plus is how it can be integrated with jQuery UI.

My most common use is to query a set of data and then output that query.

These are the steps I suggest for starting:

  1. Download DataTables from the website
  2. Copy jquery.dataTables.js from that download and place it into your scripts directory
  3. If you do not use jQuery UI, you will also have to properly set up the CSS files and images into their correct directories.
  4. I prefer to use jQuery UI and have an updated CSS file that I use. If you want to use it as a starting point, you can see it here. Most of it is the same as what came in your download. I simply made adjustments for colors, spacing, width, etc.
  5. Write your query that you will be outputting or if it's a hard-coded table, write that.
  6. Follow the code examples shown below.

Alright, we've got our script, image, and css files all set, so now it's time to code and put them to good use. I'll assume you know how to write your own query so won't show that.

Our Javascript code that will make our table a dataTable that uses a jQueryUI theme:

	
<script>
$(function() {

	$("#tbl-Mock").dataTable({ 
		"bJQueryUI": true,
		"aaSorting": []
	});	

});	
</script>
	

The ".dataTable" creates our dataTable. The "bJQueryUI" tells it to prepare for a table styled using that format. The "aaSorting" is for telling it to not automatically sort. By default, dataTables will sort your table by the first column, even if your query had sorted it using something else.

Here's the code for our table:

	
<table id="tbl-Mock">
	<thead>
		<tr>
			<th>ID</th>
			<th>Name</th>
			<th>Notes</th>
		</tr>
	</thead>
	<tbody>
		<cfoutput query="qryMock">
		<tr>
			<td>#qryMock.idRecord#</td>
			<td>#qryMock.vcName#</td>
			<td>#qryMock.vcNotes#</td>
		</tr>	
		</cfoutput>
	</tbody>
</table>	
	

Some important things to note: You must have a thead and tbody, always. You cannot use colspan.

Put them all together, and here's our table:

 
ID Name Notes
1 Jin Kazama From the Tekken series
2 Devil Jin From the Tekken series, devil version of Jin Kazama
3 Oerba Yun Fang From Final Fantasy 13
4 Vincent Valentine From Final Fantasy 7
5 Tetris A puzzle video game
6 Solid Snake From the Metal Gear series
7 Jak From the Jak series

It looks great, it can be sorted by each column, and I can search the whole table, all thanks to this great plugin.

 

<< Back to Main Work Page