Skip to content

Instantly share code, notes, and snippets.

@josephwegner
Created October 27, 2011 00:14
Show Gist options
  • Save josephwegner/1318414 to your computer and use it in GitHub Desktop.
Save josephwegner/1318414 to your computer and use it in GitHub Desktop.
A quick table sorter for Raphie
<table id="list">
<tr>
<th class='sort alpha' id='0'>Email Address</th>
<th class='sort date' id='1'>Date Added</th>
<th class='sort alpha' id='2'>Referral Link</th>
<th class='sort num' id='3'># Referrals</th>
<th>Aprove Users</th>
<th></th>
</tr>
<tr>
<td>joe@wegnerdesign.com</td>
<td>2011-07-27 09:17:30</td>
<td><a href='http://80char.com/testings'>http://80char.com/testings</td>
<td>3</td>
<td><input type="checkbox" class='bulkCheck' value="20" /></td>
<td><button onClick="document.getElementById('allUsers').value = 20;">Approve User</button></td>
</tr>
</table>
//Just a couple requirements that you will have to do:
//
// Your table MUST have an id of "list" (you can change this, it's pretty obvious where it's at in the code)
//
// Your table headers MUST have a class of "sort"
// Your table headers MUST have a class that shows the kind of data they hold ("num", "alpha", or "date")
//I think that's it.
//
// Simply run setClicks(); whenever you want the tables to sort themselves (normally on $(document).ready()
function setClicks() {
var sortables = document.getElementsByClassName("sort");
for(i=0; i<sortables.length; i++) {
sortables[i].onclick = sort;
}
}
function sort() {
sortIndex = parseInt(this.id);
var rows = document.getElementsByTagName("tr");
var header = rows[0];
var sortHead = header.getElementsByClassName('sort')[sortIndex];
header = header.innerHTML;
rows[0] = "";
var sortFunc = sortAlpha;
if(sortHead.className.indexOf("num") > -1 ) {
sortFunc = sortNum;
} else if(sortHead.className.indexOf("date") > -1) {
sortFunc = sortDate;
}
var list = document.getElementById("list");
var rowsArr = [];
for(var i=0, max=rows.length; i<max; i++) {
rowsArr.push(rows[i]);
}
rowsArr.splice(0, 1);
rowsArr.sort(sortFunc);
list.innerHTML = header;
for(var i=0, max=rowsArr.length; i<max; i++) {
list.innerHTML += rowsArr[i].innerHTML;
}
setClicks();
}
function sortAlpha(a, b) {
a = a.getElementsByTagName("td")[sortIndex].innerHTML.toUpperCase();
b = b.getElementsByTagName("td")[sortIndex].innerHTML.toUpperCase();
if(a < b) return -1
if(a > b) return 1;
return 0;
}
function sortNum(a, b) {
a = parseInt(a.getElementsByTagName("td")[sortIndex].innerHTML);
b = parseInt(b.getElementsByTagName("td")[sortIndex].innerHTML);
if(a > b) return -1;
if(a < b) return 1;
return 0;
}
function sortDate(a, b) {
a = Date(a.getElementsByTagName("td")[sortIndex].innerHTML);
b = Date(b.getElementsByTagName("td")[sortIndex].innerHTML);
if(a < b) return -1;
if(a > b) return 1;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment