Reputation: 181
This is my html code for that I put in an array to sort. I am trying to get the numbers to sort in order from the lowest to the highest (in the ids). But all my code seems to do is resort from top to bottom while maintaining the current order. Having looked around and trying a few different methods, I have not found a solution as of yet. Any suggestions?
<a href="#" class="link-sort-list asc">A-Z</a> <a href="#" class="link-sort-list desc">Z-A</a>
<ul id="sortable">
<li id="220" class="p_box"></li>
<li id="221" class="p_box"></li>
<li id="217" class="p_box"></li>
<li id="215" class="p_box"></li>
<li id="219" class="p_box"></li>
<li id="216" class="p_box"></li>
<li id="218" class="p_box"></li>
<li id="214" class="p_box"></li>
<li id="208" class="p_box"></li>
<li id="206" class="p_box"></li>
</ul>
This is my javascript sort function. The issue might be here but I am not sure.
var $list = $('#sortable');
var $myId = [];
var $myId = $(".p_box");
//Sort Click Buttons
$('.link-sort-list').click(function(e) {
if ($(this).hasClass('asc')){
$list.empty().append($myId.sort(function(a,b){return a < b}));
} else {
$list.empty().append($myId.sort());
}
e.preventDefault();
});
Upvotes: 0
Views: 65
Reputation: 11171
I would do something like this:
$("#clickme").click(function(){
var holder = [];
$("#sortable").find("li").each(function(){
holder.push($(this).attr("id"));
});
holder.sort();
var length = holder.length, i = 0, k = 0;
for (; i < length; i++){
holder[i] = $("#" + holder[i]);
}
$("#sortable").children().remove();
for (var k = length - 1; k > -1; k--){
holder[k].insertAfter($("#sortable"));
}
})
Upvotes: 1
Reputation: 318182
You have to sort by ID, and to sort the other way, reverse the condition
var $list = $('#sortable');
$('.link-sort-list').click(function(e) {
e.preventDefault();
if ($(this).hasClass('asc')) {
$list.find('li').sort(function(a, b) {
return a.id - b.id;
}).appendTo($list);
} else {
$list.find('li').sort(function(a, b) {
return b.id - a.id;
}).appendTo($list);
}
});
Upvotes: 1
Reputation: 2549
I don't see where $list
and $myId
come from but the function in sort should be:
return a - b;
Upvotes: 0