Khalifa Nikzad
Khalifa Nikzad

Reputation: 1213

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

Upvotes: 7

Views: 3065

Answers (1)

charlietfl
charlietfl

Reputation: 171679

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>

Upvotes: 6

Related Questions