Table Sorting in HTML by Javascript

This JavaScript code can be used to convert tables in ordinary HTML into sort table ones by associating each title column with an onClick event to automatically sort the data rows. No additional coding is necessary. All you need to do is give your table an ID field, include the sorttable.js file in jsp page and call init in your document's onLoad method.

JSP Page Code


< %@page contentType="text/html" pageEncoding="UTF-8"%>
< !DOCTYPE html>
< html>
< head>
< meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
< script language="javascript" src="js/sort.js">< /script>
< title>JSP Page< /title>
< style type="text/css">
#tablebox th {
background: none repeat scroll 0 0 #7da35a;
border-bottom: 1px dotted #666;
border-left: 1px dotted #666;
color: #FFFFFF;
line-height: 25px;
padding: 4px;
white-space: nowrap;
}

#tablebox td{
border-bottom: 1px dotted #666666;
border-left: 1px dotted #666666;
line-height: 12px;
padding:4px;
line-height: 20px;
white-space: nowrap;
}

#tablebox tr:hover{
background:#9cba73;
}
#tablebox thead tr {
position: relative;
}
table.sortable td {
text-align: left;
padding: 2px 4px 2px 4px;
/* width: 100px;*/
border-style: solid;
border-color: #444;
}
table.sortable tr:hover{
background:#9cba73;
}
< /style>
< /head>
< body>
< table class="sortable" id="tablebox" border="1">
< thead>
< tr>< th>MAR-2013< /th>< th>FEB-2013< /th>< th>JAN-2013< /th>< th>DEC-2012< /th>< th>NOV-2012< /th>
< th>OCT-2012< /th>< th>SEP-2012< /th>< th>AUG-2012< /th>< th>JUL-2012< /th>< th>JUN-2012< /th>
< th>MAY-2012< /th>< th>APR-2012< /th>< th>TOTAL< /th>< /tr>
< /thead>
< tbody>
< tr>< td>2146< /td>< td>1853< /td>< td>1718< /td>< td>2297< /td>< td>1909< /td>< td>1562< /td>< td>1500< /td>
< td>1555< /td>< td>1456< /td>< td>1554< /td>< td>1475< /td>< td>1582< /td>< td>20607< /td>< /tr>
< tr>< td>2389< /td>< td>1958< /td>< td>1947< /td>< td>2652< /td>< td>2129< /td>< td>1763< /td>< td>1778< /td>
< td>1788< /td>< td>1645< /td>< td>1822< /td>< td>1738< /td>< td>1841< /td>< td>23450< /td>< /tr>
< tr>< td>2616< /td>< td>2278< /td>< td>3392< /td>< td>2941< /td>< td>2226< /td>< td>2134< /td>< td>2115< /td>
< td>2328< /td>< td>2165< /td>< td>2186< /td>< td>2068< /td>< td>2134< /td>< td>28583< /td>< /tr>
< /tbody>
< /table>
< script type="text/javascript">
sorttable.init('Start');
< /script>
< /body>
< /html>

Download Sort.JS

Screenshots

Table

Table

After Sorting

After Shorting

0 comments:

Post a Comment