Reputation: 1117
I'm using this code
.wrapInner('<span title="sort this column"/>')
.each(function () {
var th = $(this),
thIndex = th.index(),
inverse = false;
th.click(function () {
table.find('td').filter(function () {
return $(this).index() === thIndex;
}).sortElements(function (a, b) {
return $.text([a]) > $.text([b]) ? inverse ? -1 : 1 : inverse ? 1 : -1;
}, function () {
// parentNode is the element we want to move
return this.parentNode;
});
inverse = !inverse;
});
});
to try and get a table to order however I keep getting the following error
TypeError: table.find("td").filter(function () {return $(this).index() === thIndex;}).sortElements is not a function
Does anyone have any clues?
Upvotes: 0
Views: 11511
Reputation: 19644
As said, you need the jquery.sortElements.js plugin.
Assuming the following markup:
<ul>
<li>Banana</li>
<li>Carrot</li>
<li>Apple</li>
</ul>
You could sort the items alphabetically like so:
$('li').sortElements(function(a, b){
return $(a).text() > $(b).text() ? 1 : -1;
});
That would result in:
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Carrot</li>
</ul>
It also lets you specify what element will be sorted. The current collection's elements will be those referred to as a and b on each call of the comparator, but you might not want those elements to be the ones to move. E.g. you might want it to be a parent. For example, when sorting a table column, you would sort by the <td>
elements, but the elements you actually want to move within the DOM are the <tr>
(each <td>
's parent):
$('td').sortElements(myComparator, function(){
// Return a reference to the desired element:
return this.parentNode;
});
See more info here: http://james.padolsey.com/javascript/sorting-elements-with-jquery/.
Upvotes: 2