Client-side Table Sorting Using Javascript

Following example will show, how to sort HTML table using javascript

Example

<!DOCTYPE HTML>
<html>
<head>
<title>Client-side Table Sorting Using Javascript</title>
<script type="text/javascript">
	var sortedOn = 0;

	function SortTable(sortOn) {

		var table = document.getElementById('results');
		var tbody = table.getElementsByTagName('tbody')[0];
		var rows = tbody.getElementsByTagName('tr');

		var rowArray = new Array();
		for (var i = 0, length = rows.length; i < length; i++) {
			rowArray[i] = new Object;
			rowArray[i].oldIndex = i;
			rowArray[i].value = rows[i].getElementsByTagName('td')[sortOn].firstChild.nodeValue;
		}

		if (sortOn == sortedOn) {
			rowArray.reverse();
		} else {
			sortedOn = sortOn;
			/*  
			 Decide which function to use from the three:RowCompareNumbers,  
			 RowCompareDollars or RowCompare (default).  
			 For first column, I needed numeric comparison.  
			 */
			if (sortedOn == 0) {
				rowArray.sort(RowCompareNumbers);
			} else {
				rowArray.sort(RowCompare);
			}
		}

		var newTbody = document.createElement('tbody');
		for (var i = 0, length = rowArray.length; i < length; i++) {
			newTbody.appendChild(rows[rowArray[i].oldIndex].cloneNode(true));
		}

		table.replaceChild(newTbody, tbody);
	}

	function RowCompare(a, b) {

		var aVal = a.value;
		var bVal = b.value;
		return (aVal == bVal ? 0 : (aVal > bVal ? 1 : -1));
	}
	// Compare number   
	function RowCompareNumbers(a, b) {

		var aVal = parseInt(a.value);
		var bVal = parseInt(b.value);
		return (aVal - bVal);
	}
	// compare currency   
	function RowCompareDollars(a, b) {

		var aVal = parseFloat(a.value.substr(1));
		var bVal = parseFloat(b.value.substr(1));
		return (aVal - bVal);
	}
</script>
</head>
<body>
	<table id="results">
		<thead>
			<tr>
				<th><a onclick="SortTable(0);" href="javascript:;">Position Jun 07</a></th>
				<th><a onclick="SortTable(1);" href="javascript:;">Position Jun 06</a></th>
				<th><a onclick="SortTable(2);" href="javascript:;">Porg.Language</a></th>
			</tr>
		</thead>
		<tbody>
			<tr style="background-color:#CCC;">
				<td>1</td>
				<td>3</td>
				<td>Java</td>
			</tr>
			<tr style="background-color:#C9EDC9;">
				<td>2</td>
				<td>8</td>
				<td>C</td>
			</tr>
			<tr style="background-color:#FEF4CD;">
				<td>3</td>
				<td>2</td>
				<td>C++</td>
			</tr>
			<tr style="background-color:#FEDCC5;">
				<td>4</td>
				<td>9</td>
				<td>VB</td>
			</tr>
			<tr style="background-color:#D5EAFF;">
				<td>5</td>
				<td>15</td>
				<td>PHP</td>
			</tr>
		</tbody>
	</table>
</body>
</html>

Output

Untitled

2 thoughts on “Client-side Table Sorting Using Javascript

  1. I implemented the above code, but still there is no effect when I click on column header. It remains stationary. Please help me out with it.

Comments are closed.