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.
This code should work for you.
$("table tr").each(function () {
$(this).find("td").eq(1).after($(this).find("td").eq(0));
});
$("table tr").each(function () {
var rows = $(this).find("td");
rows.eq(1).after(rows.eq(0));
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With