HTML table formatting with jQuery
After a few years of web development, it becomes apparent to a programmer that there are a set of additional tasks that must be completed before a page that displays database data in table form can be considered ready for production. This set of tasks cuts across programming languages (since it all becomes HTML and JavaScript in the end).
A couple of the really basic ones are (a) alternation of background row colors, and (b) ability to sort the table's data on any of its columns, usually by clicking on the column's header. Six years back when I started web programming professionally, both of these had to be written by hand. The row color alternation was accomplished by calculating the row count modulus two to get either zero or one and calling different CSS classes for each. Though not difficult, this requires insertion of an awkwardly long formula directly in the web page code (regardless of whether it is php, perl, jsp, etc). Sorting column data was always harder as it required executing a new database query that sorted on the correct field. Building the query string with the new sort clause was tricky and sometimes required using a GET on a URL with the sort criteria embedded.
Fortunately a few years ago a JavaScript library called jQuery became popular and can either accomplish both of these tasks separately (without massive amounts of code or difficult code) or in a combined approach. Treated separately, the table sorter feature can break the row color alternation (rows maintain their original background color after being sorted). The table sorter plugin has a "zebra" widget that performs both functions and maintains proper row color alternation after sorts.
Briefly, to activate these two jQuery features, follow these steps:
Briefly, to activate these two jQuery features, follow these steps:
- Download the regular development jquery.js file and the table sorter files
- Add the two .js files (libraries) to your project (under a web-accessible directory)
- Import the two library files into the web page in the "head" section
- Write the jQuery method, also in the "head" section, enclosed in the "document.ready" function piece. For the the zebra widget, define the "tablesorter" function and call the widget inside that (see code below)
- Define CSS classes for tr.even and tr.odd, giving each a background color
- Wrap the data table header with "thead" and "th" tags
- Wrap the data table content with the "tbody" tag
$(document).ready(function(){
$("table").tablesorter({
widgets: ['zebra']
});
});
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home