BHAGVAT GITA
<html> <head> <meta charset=“utf-8” /> <title>Alphabetized Table</title> </head> <body>
<h1>This table should get automagically sorted and have alphabet links</h1> <!-- the alphabet nav will get added by the js and only existing items will have links --> <table class="alphabetize-me"> <thead> <tr> <th>Name</th> <th>Other info</th> </tr> </thead> <tbody> <!-- the order of these is unimportant since they will be sorted by JS --> <tr><td>Banana</td><td>bat</td></tr> <tr><td>Apple</td><td>cat</td></tr> <tr><td>Dodecahedron</td><td>ant</td></tr> <tr><td>Cherry</td><td>antelope</td></tr> <tr><td>Dog</td><td>cow</td></tr> <tr><td>Cat</td><td>bull</td></tr> <tr><td>lion</td><td>bear</td></tr> <tr><td>tiger</td><td>boar</td></tr> </tbody> </table>
<script src=“ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”></script> <script>window.jQuery || document.write('<script src=“http://code.jquery.com/jquery-1.7.2.min.js”><\/script>')</script> <script> (function ($) { $(function () { var linkTemplate = “<a href='#{href}'>{html}</a>”, findHref = /\{href\}/g, findHtml = /\{html\}/g; $(“table.alphabetize-me”).each(function () { var $table = $(this), $rowBody = $table.find(“>tbody”), only get rows in tbody element (skip table headers)
$dataRows = $rowBody.find(">tr"), sortColumn = 0, uniqueTableId = "table-" + (new Date()).valueOf(); // sort array based on sortColumn (set to 0 above) $dataRows.sort(function (a, b) { var $a = $(a), $b = $(b), aVal = $a.find(">td:eq(" + sortColumn + ")").text().toLowerCase(), bVal = $b.find(">td:eq(" + sortColumn + ")").text().toLowerCase(); $a.attr("data-sort-text", aVal); $b.attr("data-sort-text", bVal); if (aVal < bVal) return -1; else if (aVal > bVal) return 1; else return 0; }); $rowBody.empty().append($dataRows); // loop through and build alphabet nav var nav = ""; for (var i = "A".charCodeAt(0); i <= "Z".charCodeAt(0); i++) { var letter = String.fromCharCode(i), // look for first row that starts with the letter $tr = $dataRows.filter("[data-sort-text^='" + letter.toLowerCase() + "']:eq(0)"), rowId = letter + "-" + uniqueTableId; nav += " "; if ($tr.length > 0) { $tr.attr("id", rowId); nav += linkTemplate.replace(findHref, rowId).replace(findHtml, letter); } else { nav += letter; } } $("<div class='alphabet'>" + nav + "</div>").insertBefore($table); }); });
Discussion