There are many ways to sort a table containing tabular data. A common approach is to perform the sort on the server using ASP or something similar, maybe out of routine using the same thought pattern as in ordinary desktop applications.
An alternative for web pages is to do it with client-side scripting. One advantage is that all activity takes place on the client side, thus avoiding any unnecessary round-trip to the server.
Below is an example. Click on the column headers to sort the column alphabetically.
Title | Director | Release date |
---|---|---|
Casablanca | Michael Curtiz | 1942 |
Citizen Kane | Orson Welles | 1941 |
Its a Wonderful Life | Frank Capra | 1946 |
Metropolis | Fritz Lang | 1927 |
North by Northwest | Alfred Hitchcock | 1959 |
Markup
The HTML markup looks like this:
Next, insert links into the header and use the onclick event to call a JavaScript function.
Using the onclick attribute is not best practice, we should do it the proper way with event handlers, but this is only for demonstration purposes.
JavaScript
The simple implementation works as follows:
- Get all rows in our table
- For each row, get the data of selected column and store it in an array along with the index
- Sort the column data
- Select order of table rows using the sorted index and copy them to a new table body
- Replace old table body with sorted table body
This is quite easily done using the DOM. The rows are fetched by the usual getElement methods. Sorting is performed by two custom functions, depending on type of table column content. For the copy I use cloneNode, the DOM equivalent of innerHTML.
function Compare(x, y) { var xValue = x.value; var yValue = y.value; return (xValue == yValue ? 0 : (xValue > yValue ? 1 : -1)); }
function CompareDigits(x, y) { var xValue = parseInt(x.value); var yValue = parseInt(y.value); return (xValue – yValue); }
//–> </script> </head> <body> <h1>Table sort example</h1> <table id="movies" border="1"> <thead> <tr> <th><a href="javascript:;" onclick="SortTable(0);">Title</a></th> <th><a href="javascript:;" onclick="SortTable(1);">Director</a></th> <th><a href="javascript:;" onclick="SortTable(2);">Release date</a></th> </tr> </thead> <tbody> <tr> <td>Casablanca</td> <td>Michael Curtiz</td> <td>1942</td> </tr> <tr> <td>Citizen Kane</td> <td>Orson Welles</td> <td>1941</td> </tr> <tr> <td>Its a Wonderful Life</td> <td>Frank Capra</td> <td>1946</td> </tr> <tr> <td>Metropolis</td> <td>Fritz Lang</td> <td>1927</td> </tr> <tr> <td>North by Northwest</td> <td>Alfred Hitchcock</td> <td>1959</td> </tr> </tbody> </table> </body> </html>Easy as pie. Good luck!
Related posts
8 comments
Leave a reply