Sort table columns with jQuery table sorter

I was wondering if there is a way to sort columns with a table sorter
So that I can independently arrange the columns according to some kind of identifier or something else.
alt text

So, for example, if I want to sort the table so that the Apple column
Would be the first how do I do this?

+4
source share
4 answers

Demo: http://jsfiddle.net/fKMqD/

the code:

var rows = $('tr'); rows.eq(0).find('td').sort(function(a, b){ return $.text([a]) > $.text([b]) ? 1: -1; }).each(function(newIndex){ var originalIndex = $(this).index(); rows.each(function(){ var td = $(this).find('td'); if (originalIndex !== newIndex) td.eq(originalIndex).insertAfter(td.eq(newIndex)); }); }); 

No plugins required.

+1
source

There is a plugin for jquery called datatable, it is very easy to use, like most plugins, and does everything you need on the fly, without extra work.

http://www.datatables.net/

check it out.

+1
source

I worked on it

 <html> <head> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("jquery", "1"); </script> <script> $(function() { // Figure out the new column order. var isWas = {}; $("tr").eq(0).find("td").each(function(index) { $(this).attr("was", index); }).sort(function(left, right) { // Change this line to change how you sort. return $(left).text() > $(right).text() ? 1 : -1; }).each(function(index) { isWas[index] = $(this).attr("was"); }); // Reorder the columns in every row. $("tr").each(function() { var tr = $(this); var tds = tr.find("td"); var newOrder = []; for (var is = 0; is < tds.length; is++) { newOrder.push(tds.eq(isWas[is])); } for (var is = 0; is < tds.length; is++) { tr.append(newOrder[is]); } }); }); </script> </head> <body> <table> <tr><td>Potato</td><td>Tomato</td><td>Apple</td></tr> <tr><td>20g</td><td>10gr</td><td>40gr</td></tr> </table> </body> </html> 
0
source

Source: https://habr.com/ru/post/1314011/


All Articles