I have a table like this, column 3 is a column of checkbox

header1   header2     header3
 cell1     cell2     checkbox3
 cell1     cell2     checkbox3
 cell1     cell2     checkbox3

I want to move column 3 to after column 1 like this

header1     header3      header2
 cell1     checkbox3      cell2
 cell1     checkbox3      cell2
 cell1     checkbox3      cell2

This is what I tried so far:

$('thead tr:nth-child(2)').insertAfter('thead tr:nth-child(0)');
$('tbody tr:nth-child(2)').insertAfter('tbody tr:nth-child(0)');

Code for table:

<table>
  <thead>
   <tr>
    <th>header1</th>
    <th>header2</th>
    <th>header3</th>
   </tr>
  </thead>
  <tbody>
   <tr>
    <td>cell1</td>
    <td>cell2</td>
    <td><input type="checkbox" />checkbox3</td>
   </tr>
   <tr>
    <td>cell1</td>
    <td>cell2</td>
    <td><input type="checkbox" />checkbox3</td>
   </tr>
   <tr>
    <td>cell1</td>
    <td>cell2</td>
    <td><input type="checkbox" />checkbox3</td>
   </tr>
  </tbody>
</table>

But it didn't work, any idea that I can solve this?

1 Answers

0
AndroidNoobie On

How about something like this:

function swapColumns (table, sourceCol, destCol) {
    let rows = $("tr", table);  // get rows in table
    let cols;   // declare cols variable
    rows.each(function() {
        cols = $(this).children("th, td");  // cols include th and td
        cols.eq(sourceCol).detach().insertBefore(cols.eq(destCol)); // swap 'em
    });
}

let table = $("#tableSelector");
swapColumns(table);