Main Page

Sorting a Multicolumn Table

Figure 12-2
All that’s left to do is to call the function when the user clicks on the column header. You can do this in
any number of ways, but the simplest is just to add the function call as the
<th/>
element’s
onclick
event handler:
<table border=”1” id=”tblSort”>
<thead>
<tr>
<th onclick=”sortTable(‘tblSort’)”
style=”cursor:pointer”>Last Name</th>
</tr>
</thead>
<tbody>
<!-- data rows -->
</tbody>
</table>
Also note the
style
attribute has been set to
cursor:pointer
, which ensures that the cursor turns into
the hand pointer when the user mouses over the column header.
At this point, you just click on the column header to sort all the last names in alphabetical order.
Sorting a Multicolumn Table
In practice, it’s very rare to have a single-column table, which is why the next task is to sort a table with
more than one column. Suppose you added a second column to the table in the previous example, per-
haps to display the first name of a person in addition to the last name:
<table border=”1” id=”tblSort”>
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
</tr>
</thead>
<tbody>
<tr>
<tr>
<tr>
<tbody>
<tbody>
<tr>
<tr>
<tr>
<tr>
Fragment
<tr>
<tr>
373
Sorting Tables
15_579088 ch12.qxd 3/28/05 11:40 AM Page 373


JavaScript EditorFree JavaScript Editor     Ajax Editor


©