Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder table column position in jquery

I have the following table and want to reorder the table column according to the <th> position attribute value with jquery after the page is loaded.

I looked at the following solutions but couldn't solve my problem:

  1. jQuery re-ordering table columns
  2. Re-order table columns?
  3. Change table columns order

<table>
    <head>
        <tr>
            <th position = "3">Email</th>
            <th position = "1">Name</th>
            <th position = "2">Phone</th>
        </tr>
    </head>
    <tbody>
        <tr>
            <td>[email protected]</td>
            <td>Hamid</td>
            <td>0776567432</td>
        </tr>
    </tbody>
</table>

The expected result: enter image description here

like image 899
Khalifa Nikzad Avatar asked Mar 24 '19 09:03

Khalifa Nikzad


1 Answers

Create an object from the position attributes using the <th> index as keys.

Then use that object in a sort() callback to look up new order for each element

const colOrder = {}

$('thead th').each(function(i){
    colOrder[i] = parseInt( $(this).attr('position') );
});


$('tr').html(function(i){
    return $(this).children().sort(function(a,b){
       const aOrder = colOrder[$(a).index()],
            bOrder = colOrder[$(b).index()];
       return aOrder - bOrder;
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <thead>
        <tr>
            <th position = "3">Email</th>
            <th position = "1">Name</th>
            <th position = "2">Phone</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>[email protected]</td>
            <td>Hamid</td>
            <td>0776567432</td>
        </tr>
    </tbody>
</table>
like image 89
charlietfl Avatar answered Oct 12 '22 22:10

charlietfl