Reputation: 99
I have a div table like for a page, is it possible to make it sortable like html table with javascript?
I moved from normal table because it was not possible for me to continue using it due to this How to add td rowspans to a table? and thus used the div table.
so I used this div table and the only thing im missing is how to make it sortable so I can sort it by item or price.. like datatables, tablesorter e.t.c
<div class="Header">
<div class="item"><a href="#">Item</a>
</div>
<div class="desc"><a href="#">Description</a>
</div>
<div class="price"><a href="#">Price</a>
</div>
<div class="status"><a href="#">Status</a>
</div>
</div>
<div class="Info">
<div class="itemName">
<div class="item">Item 1</div>
</div>
<div class="itemInfo">
<div class="List">
<div class="Desc">Description 1</div>
<div class="Box">
<div class="price">$79</div>
<div class="status">16 in stock</div>
</div>
</div>
</div>
</div>
full code here http://codepen.io/anon/pen/empqyN?editors=110 and here http://jsfiddle.net/a4fcxzra/
Upvotes: 4
Views: 2319
Reputation: 16068
Here is a sorting handler: (the header classes need to be the same as where the info is, so changed in the header desc to Desc)
var sorting=1;
$(".Header div").each(function(){
$(this).click(function(){
var cl=$(this).attr("class") // get header class, this is where I get info from
sorting = sorting == 1 ? -1 : 1 ; // sorting asc or desc
$(".Info").detach().sort(function(a,b){
var str1=$(a).find('.'+cl).text(); // get text
var str2=$(b).find('.'+cl).text();
var n1 = str1.match(/\d+/)[0] //get digits in text
var n2 = str2.match(/\d+/)[0]
if(n1 != '' ){ // if its a number
return n1*sorting > n2*sorting; // sort by number
}else{ // sort by string
return sorting == 1 ? str1 > str2 : str1 < str2
}
}).appendTo($(".Header").parent());
})
})
Working Fiddle: http://jsfiddle.net/juvian/a4fcxzra/1/
Upvotes: 3
Reputation: 11
You can sort an Array using JavaScript and then creating tags dynamically to place them within the column headers (which you should create in the html for better performance)
Upvotes: 0