Change table columns order

I need to change the order of columns in a table in html / js dynamically, you can tell me how to do it?


Solution 1:

If you only require to simply move a column without any fancy drag-drop animation, the following JS should do the trick:

<script type="text/javascript">
    $(function() {
        jQuery.each($("table tr"), function() { 
            $(this).children(":eq(1)").after($(this).children(":eq(0)"));
        });
    });
</script>

Replacing the numbers as necessary. The concept works

It seems that writing this as a one liner isn't really possible. including td in the selector, even with the row selector seems to hold each td on a separate index, ignoring rows.

A jQuery grid plugin should do the trick otherwise. Although I have no experience with such plugins.

Solution 2:

Moving columns is not that hard:

You can use this function:

jQuery.moveColumn = function (table, from, to) {
    var rows = jQuery('tr', table);
    var cols;
    rows.each(function() {
        cols = jQuery(this).children('th, td');
        cols.eq(from).detach().insertBefore(cols.eq(to));
    });
}

Then invoke it like so:

var tbl = jQuery('table');
jQuery.moveColumn(tbl, 2, 0);

So, by knowing the index of the column, and the index of where you'd like to put it (zero-based), you can move the columns, including column headings.

Here is the working jsfiddle: http://jsfiddle.net/Qsys7/1/

Solution 3:

Here's a jQuery plugin I just wrote to switch the contents of two columns:

$.fn.switchColumns = function ( col1, col2 ) {
    var $this = this,
        $tr = $this.find('tr');

    $tr.each(function(i, ele){
        var $ele = $(ele),
            $td = $ele.find('td'),
            $tdt;

        $tdt = $td.eq( col1 ).clone();
        $td.eq( col1 ).html( $td.eq( col2 ).html() );
        $td.eq( col2 ).html( $tdt.html() );
    });
};

See example →