JavaScript

How to Sort a Table by Clicking the Header (th) Tag Using jquery.tablesorter.js

Here’s how you can use jquery.tablesorter.js to sort a table by clicking its header (th) tags, sorting the corresponding elements (td tags) in ascending or descending order.

CSS for Sorting the Table

Modify as needed.

<style type="text/css">
<!--
body {
	margin: 0px;
	font-size:14px;
}
h1{
	font-size:16px;
	font-weight:normal;
	line-height:1.4em;
	text-align:center;
	padding:15px 0 10px 0;
}
#idWrap{
	width:700px;
	margin:0 auto;
}
table{
	border:solid 1px #333333;
}
th{
	background-color:#333333;
	color:#FFFFFF;
	border-bottom:solid 1px #333333;
	cursor:pointer;
}
th:hover{
	background-color:#FFFFFF;
	color:#333333;
	border-bottom:solid 1px #333333; 
}
th, td{
	padding:10px;
	font-weight:normal;
}
-->
</style>

JavaScript for Sorting the Table Using jquery.tablesorter.js

Load the jQuery and jquery.tablesorter.js files. Specify the table you want to sort using $(‘#myTable’).tablesorter().

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="jquery.tablesorter.js"></script>
<script type="text/javascript">
$(function(){
	$('#myTable').tablesorter();
});
</script>

HTML for the Sortable Table Using jquery.tablesorter.js

Here is the HTML for the table you want to sort. Clicking the header (th) tags will sort the corresponding elements (td tags) in ascending or descending order.

<table id="myTable" cellpadding="0" cellspacing="0"> 

<thead> 

<tr>

<th>No</th>


<th>Category</th>


<th>URL</th>

</tr>

</thead>


<tbody>

<tr>

<td>1</td>


<td>css</td>


<td><a href="https://dad-union.com/category/css" target="_blank">https://dad-union.com/category/css</a></td>

</tr>


<tr>

<td>2</td>


<td>JavaScript</td>


<td><a href="https://dad-union.com/category/javascript" target="_blank">https://dad-union.com/category/javascript</a></td>

</tr>


<tr>

<td>3</td>


<td>jQuery</td>


<td><a href="https://dad-union.com/category/jquery" target="_blank">https://dad-union.com/category/jquery</a></td>

</tr>


<tr>

<td>4</td>


<td>PHP</td>


<td><a href="https://dad-union.com/category/php" target="_blank">https://dad-union.com/category/php</a></td>

</tr>

</tbody>

</table>

Demo Page for a Sortable Table

Demo Page for a Sortable Table

The compatible browsers include IE 6.0+, FF 2+, Safari 2.0+, and Opera 9.0+. It seems to work fine on Chrome as well.

 
Please use at your own risk. Do not reuse the Google Analytics tag from the demo page.