Naveed
Naveed

Reputation:

jQuery: Sort a table column not rows

I want to sort a table by column's head field. Means I want to keep the rows at same place but order of columns should be sort based on column heading field(td).

For Example:

table before sorting:

assign1|assign3|assign2|assign4|
assign1|assign3|assign2|assign4|
assign1|assign3|assign2|assign4|
assign1|assign3|assign2|assign4|
assign1|assign3|assign2|assign4|
assign1|assign3|assign2|assign4|
assign1|assign3|assign2|assign4|

and after sorting:

assign1|assign2|assign3|assign4|
assign1|assign2|assign3|assign4|
assign1|assign2|assign3|assign4|
assign1|assign2|assign3|assign4|
assign1|assign2|assign3|assign4|
assign1|assign2|assign3|assign4|
assign1|assign2|assign3|assign4|

@seth I have to sort(change order) of columns with headers.

@CMS I have tried tablesorter plugin and this plugin sort rows. Means it changes the order of rows in ascending or descending order.

But my problem is different I have to change the order of columns with their header cell in ascending or descending order.

please look at my example in question.

Upvotes: 0

Views: 5341

Answers (2)

seth
seth

Reputation: 37277

Ok, here's something I whipped up. It's not the most elegant or cleanest probably but it works.

// sorting function for the headers
function th_sorter(a, b) {
   // just compare the text
   var cmp = $(a).text() > $(b).text();
   if (cmp) {
     return 1;
   }
   else {
     return $(a).text() === $(b).text() ? -1 : 0;
   }
}

var sorted = [], temp=[];
// first sort the 1st row so we can figure out what goes where
$('table tr:first').each(
  function(i, tr) {
      $(tr).children('td').each( function(idx,node) {
        $(node).data('orig', idx);
      }).sort( th_sorter ).each( function(idx, node) {
        sorted.push( { 
            html: $(node).html(), 
            idx: $(node).data('orig') 
          } );
      });
});

// now re-arrange the deck chairs
$('table tr').each( function(i, tr) {
  // double each, once to capture and once to move                                          
  $(tr).children('td').each( function( idx, node) {
    temp[idx] = $(node).html();
  }).each( function(idx,node) {
    $(node).html( temp[ sorted[idx].idx ] );
  });
  temp = [];
});

Demo page

Upvotes: 4

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827446

Give a look to this plugin:

Upvotes: 1

Related Questions