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:
<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:
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>
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