Saturday, January 30, 2016

How to add jQuery TableSorter

In this blog post I am going to demonstrate how to add a table sorter to a HTML table.

Prerequisites
1.jquery.min.js [download]
2.jquery.tablesorter.min.js [download]
Code
index.html
       
 
<html>
<head>
<title>TableSorter Demo</title>
<!-- link to css file -->
<link href="css/style.css" rel="stylesheet"></link>
<!-- Jquery library -->
<script src="js/jquery.min.js" type="text/javascript"></script>
<!-- Jquery tablesorter library -->
<script src="js/jquery.tablesorter.min.js" type="text/javascript"></script>
<script src="js/table.js" type="text/javascript"></script>
<script>
 $(function() {
  $("#demoTable").tablesorter();
 });
</script>
</head>
<body>
 <table id="demoTable">
  <thead>
<tr>
    <th class="sortUpImg">Name</th>
    <th class="sortUpImg">Age</th>
   </tr>
</thead>
  <tbody id="rows">
  </tbody>
 </table>
</body>
</html> 
           
       
 

table.js
       
$(function() {
 // JSON data array
 var employees = [ {
  "Name" : "John",
  "Age" : "20"
 }, {
  "Name" : "Ann",
  "Age" : "15"
 }, {
  "Name" : "Peter",
  "Age" : "60"
 } ];
 // bind the data with tbody
 for (var i = 0; i < employees.length; i++) {
  $("#rows").append(
    "" + employees[i].Name + "<br />
"
      + employees[i].Age + "<br />
");
  
  $("#demoTable").trigger("update");

 }

});           
       
 

style.css
       
table {
 border-collapse: collapse;
 width: 100%;
}

td {
 text-align: left;
 padding: 5px;
 border: 1px solid #ddd;
}

tr:nth-child(even) {
 background-color: #F9B36D
}

th {
 
}

.sortUpImg {
 background: url(../img/bg.gif) no-repeat 99%;
 background-color: #F77D03;
 color: white;
 padding: 15px;
 text-align: left;
 border: 1px solid #ddd
}  
         
       
 

Download the source code. [Click Here]