tags:

views:

1504

answers:

4

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|
+1  A: 

Give a look to this plugin:

CMS
A: 

@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.

You should reply to comments in the comments to the answers, not as an answer.
seth
+3  A: 

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

seth
A: 

Thankyou very much. It is working perfectly in demo. It is very helpful for me as I am working first time with jquery.

It is first time that I am using this forum and dont know how to comment on user's answer :)

Anyway Thanks.

Naveed riksof.com