I know there are a lot of plugins for table sorting, but I would like to learn it myself. So here is my table.
<table class="table-bordered sortable">
<tr>
<th>Name</th>
<th>Wage</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>Jack Carver</td>
<td>368</td>
<td>45</td>
<td>New York</td>
</tr>
<tr>
<td>John Johnson</td>
<td>450</td>
<td>19</td>
<td>Atlanta</td>
</tr>
<tr>
<td>Steve McKenzie</td>
<td>891</td>
<td>88</td>
<td>Miami</td>
</tr>
</table>
How can I make my table sortable? If user clicks on th, relevant tds should be sort alphabetically (and rest of row as well).
Here is a general approach. No one step is particularly difficult, it's just sometimes hard to put everything together:
<th>
elements<tr>
elements, and put those into an array.<tr>
elements with Array.sort()
. The sorting function will need to look at the contents of <td>
child element of the <tr>
passed in with the same index as the <th>
element clicked.<tbody>
and reinsert the <tr>
s in the sorted order.<th>
to indicate that it is sorted.Now I wouldn't use the result of this technique in production because it is quite fragile and we shouldn't be manipulating DOM directly in this fashion, but at least it is a good exercise to develop JS skills.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments