3

There is a html table in this fiddle which is created as

<table width="100%" border="1" cellpadding="0" cellspacing="0">
    <tr>
        <th>Sl.No</th>
        <th>Name</th>
        <th>Dec 2013</th>
        <th>Feb 2014</th>
        <th>Jan 2014</th>
        <th>Mar 2014</th>
        <th>Nov 2013</th>
        <th>Total</th>
    </tr>
    <tr>
        <td>1</td>
        <td>foo</td>
        <td>4</td>
        <td>7</td>
        <td>3</td>
        <td>5</td>
        <td>2</td>
        <td>21</td>
    </tr>
    <tr>
        <td>2</td>
        <td>bar</td>
        <td>6</td>
        <td>1</td>
        <td>5</td>
        <td>8</td>
        <td>3</td>
        <td>23</td>
    </tr>
</table>

How to re-order the columns using jquery so that the order of the columns in new table becomes Sl.No, Name, Nov 2013, Dec 2013, Jan 2014, Feb 2014, Mar 2014, Total Also the month columns are generated dynamically by server based on date selection (From and To dates)

3
  • Why don't you sort the data on the server? Commented Apr 4, 2014 at 4:29
  • I suggest you use ORDER BY in the Query you use to retrieve data ! This reduces the JS load if there's any on client side ! Commented Apr 4, 2014 at 5:05
  • @undefined - Me sorted data in server side. But at client side it taking the order in alphabetical manner. ie like Dec 2013 Feb 2014 etc. Commented Apr 4, 2014 at 5:22

1 Answer 1

1
var arr = $('th').sort(function(a, b) {
   return new Date(a.innerHTML) > new Date(b.innerHTML);
}).map(function() { return this.cellIndex }).get();

$('tr').each(function() {
    $(this.cells).sort(function(a, b) {
        a = $.inArray(a.cellIndex, arr);
        b = $.inArray(b.cellIndex, arr);
        return a > b;
    }).prependTo(this);
});

http://jsfiddle.net/ZR5W7/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.