This is a stand-alone version of Example 1 from DHTML Sorting Using OOP.
Click on a column header to sort by that column, or use the form below.
Instructions for implementation
Before proceeding you should view the source code for this page as everything you need is visible there - and clearly marked. The code has been stripped down to make it as understandable as possible.
Then we need to properly mark up and reference the data to be sorted. This means using a TABLE structure similar to the following:
<table> <thead> <!-- rows to be preserved --> </thead> <tbody id="data"> <!-- rows to be sorted --> </tbody> </table>
Now that we've (hopefully) successfully initialised the shellSort object, we can use it's single public function:
sortTable.sort(0); // sort by 1st column (ascending) sortTable.sort(1, true); // sort by 2nd column (descending) sortTable.sort(2, false, 'a'); // sort on contents of first 'a' node in 3rd column (ascending)
In this example, the links at the top of each column will sort by that column, using the direction indicated by the checkbox in the form below the table.
The form provides a similar functionality. When a value is chosen in the select box or the checkbox is clicked, the table is sorted by the selected column, in the direction indicated by the checkbox.
As mentioned previous, to use a different sort algorithm you need to:
- instantiate the corresponding class ('shellSort' in this example).
Questions or comments or want to tell us how you're using the code? Use the feedback link below.
Related Articles - Sorting Algorithms
- PHP Sorting Arrays of Arrays
- PHP Sorting SimpleXMLElement Object arrays
Send a message to The Art of Web:
press <Esc> or click outside this box to close