Use jQuery to sort the rows of an html table according to one or more values in each row.
The example sorts a list of names, so first some initial values for the list.
<?php
$all_names = array ('Franz', 'Andrew', 'Greg', 'Ryan', 'Matt');
?>
Create a table
Now we turn the list of names into rows of a table. The containing form and associated submit button have been left out just to keep this simple.
<table id="sortable_table">
<tr><td><?php echo 'Sort Names';?></td><td></td></tr>
<?php
foreach($all_names as $a_name) { ?>
<tr class="sortable_row">
<td><input type="hidden" name="all_names[]" value="<?php echo $a_name ?>" ><?php echo $a_name ?></td>
</tr><?php
}?>
</table>
To make it work, we also need a button to click on to start the sort:
<input type="button" id="sort_now" value="Sort Now">
jQuery to Sort the Table
The jQuery to do the sort is attached to the click event for the button.
<script type="text/javascript">
$(document).ready(function(){
$('#sort_now').click(function(ev){
// a simple compare function, used by the sort below
var compare_rows = function (a,b){
var a_val = $(a).text().toLowerCase();
var b_val = $(b).text().toLowerCase();
if (a_val>b_val){
return 1;
}
if (a_val<b_val){
return -1;
}
return 0;
};
// the actual sort
$('#sortable_table .sortable_row').sort(compare_rows).appendTo('#sortable_table');
});
});
</script>
The important line is towards the bottom of the code. This gets all the applicable rows as an array of jQuery objects, applies the regular javascript sort to them, then appends the sorted array of rows back to the table they came from. In the process, the appendTo method actually moves the rows from where they were originally, so we are left with a sorted table.
Inside the sort, compare_rows is a sort function similar to that used by sorting in most programming languages. Its job is to compare a and b, returning 1,0,-1 depending on which is greater. Here just the lowercase text for the name is used. But it could just as easily take the value of a form element, or use multiple values from a row to give greater discretion.
Back on the Server
As already noted above, a form and submit button are needed to wrap the table to submit it. When the form is subsequently submitted, the relevant controller or tool on the server can get the rows in order.
$all_names = $_POST['all_names'];
Taking it Further
This is a useful technique for combining with a dynamic list of input elements (though not to be confused with drag/drop sorting).
The application of this technique is not limited to table rows, it can just as easily be attached to any other list, including HTML list elements.