7

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

1 Answer 1

6

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>

1
  • this is not working if I run code snippet @charlietfl Please explian Nov 12, 2022 at 5:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.