exclude rows

tablesorter jQuery – how to exclude rows

Posted on: May 10th, 2013 by taff 8 Comments

 

The tablesorter plugin from jQuery is great when I have some data which I want to sort.

Calling

$("#tmp").tablesorter();

would allow me to sort markup such as by clicking on the headers:

<table class="tablesorter" id="tmp">
	<thead>
		<tr>
			<th>Area</th>
			<th>Total Visitors</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>Javascript</td>
			<td>15</td>
		</tr>
		<tr>
			<td>PHP</td>
			<td>3</td>
		</tr>
		<tr>
			<td>HTML5</td>
			<td>32</td>
		</tr>
		<tr>
			<td>CSS</td>
			<td>14</td>
		</tr>
		<tr>
			<td>XML</td>
			<td>54</td>
		</tr>
		<tr>
			<td><strong>Total</strong></td>
			<td><strong>118</strong></td>
		</tr>
	</tbody>
</table>

Easy peasy...No wait, I dont like how it is sorting the totals which are bold.
Sorting the Total Visitors row only would make it better and I could accomplish it by changing my javascript tablesorter call to

$("#tmp").tablesorter({
	headers: { 
		1: { 
			sorter: false 
		} 
	} 
});

which disables clicking of the second field (1 is the second field here, as 0 is the first, thus disabling a column. This makes it a little tidier but not really what we want. Ideally we want it to sort all the rows but leave the last one alone.

Not including the last row when sorting

I looked online and found a plugin which allows for static data whilst sorting.
Sounds like a little bit of an overkill for our example so I looked at how tablesorter works. The HTML needs to have a specific setup with thead and tbody tags.
So theoretically I could put my last row into a tfoot tag and it wouldnt be affected by sorting. So off I went and updated my markup to

<table class="tablesorter" id="tmp">
	<thead>
		<tr>
			<th>Area</th>
			<th>Total Visitors</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>Javascript</td>
			<td>15</td>
		</tr>
		<tr>
			<td>PHP</td>
			<td>3</td>
		</tr>
		<tr>
			<td>HTML5</td>
			<td>32</td>
		</tr>
		<tr>
			<td>CSS</td>
			<td>14</td>
		</tr>
		<tr>
			<td>XML</td>
			<td>54</td>
		</tr>
	</tbody>
	<tfoot>
		<tr>
			<td><strong>Total</strong></td>
			<td><strong>118</strong></td>
		</tr>
	</tfoot>
</table>

and hey presto it works. I hope this comes in handy for someone trying to sort columns with the jQuery tablesorter plugin apart from the last one(s).