Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-order table columns?

Does anyone know a way to re-order table columns, using jQuery?

I don't mean sort - I mean dynamically move entire columns left or right in a table.

I'm aware of the excellent dragtable plugin, but I don't need something that allows the user to move columns, I need something that will do the re-ordering in a configurable way.

like image 964
Richard Avatar asked Jul 20 '11 08:07

Richard


2 Answers

This code should work for you.

$("table tr").each(function () {
    $(this).find("td").eq(1).after($(this).find("td").eq(0));
});


Edit: If you assign $(this).find("td") to a variable this would give better performance. But the context was down to a single tr. So i assumed it would be enough just to give the idea.
$("table tr").each(function () {
    var rows = $(this).find("td");
    rows.eq(1).after(rows.eq(0));
});
like image 83
Yiğit Yener Avatar answered Sep 29 '22 02:09

Yiğit Yener


The idea is to walk over all rows (tr's) of the table and swap the desired td's. Let's swap column 2 and column 4:

$('table tr').each(function() {
    var tr = $(this);
    var td1 = tr.find('td:eq(1)'); // indices are zero-based here
    var td2 = tr.find('td:eq(3)');
    td1.detach().insertAfter(td2);
});

I hope this helps.

like image 30
scaryzet Avatar answered Sep 29 '22 02:09

scaryzet