Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort HTML table by Javascript

I have the following HTML table which I wanted to be sorted by data-sku=""

( function() {
        $("table tbody tr").sort(sort_table).appendTo('table tbody');
            function sort_table(a, b) {
            return ($(b).data('sku')) < ($(a).data('sku')) ? 1 : -1;
        }
} )();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="abp-product-42" data-id="42" data-sku="A-04-0002"><td>A-04-0002</tr>
<tr class="abp-product-21" data-id="21" data-sku="A-04-0011"><td>A-04-0011</td></tr>
<tr class="abp-product-391" data-id="391" data-sku="A-02-0008"><td>A-02-0008</td></tr>
<tr class="abp-product-393" data-id="393" data-sku="A-02-0007"><td>A-02-0007</td></tr>
<tr class="abp-product-40" data-id="40" data-sku="A-04-0010"><td>A-03-0010</td></tr>
<tr class="abp-product-390" data-id="390" data-sku="A-03-0003"><td>A-04-0003</td></tr>
</tbody>
</table>

But somehow it doesn’t work – what I’m doing wrong or what I’m missing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This will call your function in every 5 seconds like I mentioned in the comment.

window.setInterval(function(){
 sortData();
}, 5000);

function sortData(){
 $("table tbody tr").sort(sort_table).appendTo('table tbody');
            function sort_table(a, b) {
            return ($(b).data('sku')) < ($(a).data('sku')) ? 1 : -1;
        }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="abp-product-42" data-id="42" data-sku="A-04-0002"><td>A-04-0002</tr>
<tr class="abp-product-21" data-id="21" data-sku="A-04-0011"><td>A-04-0011</td></tr>
<tr class="abp-product-391" data-id="391" data-sku="A-02-0008"><td>A-02-0008</td></tr>
<tr class="abp-product-393" data-id="393" data-sku="A-02-0007"><td>A-02-0007</td></tr>
<tr class="abp-product-40" data-id="40" data-sku="A-04-0010"><td>A-04-0010</td></tr>
<tr class="abp-product-390" data-id="390" data-sku="A-03-0003"><td>A-03-0003</td></tr>
<tr class="abp-product-390" data-id="390" data-sku="A-05-0003"><td>A-05-0003</td></tr>
</tbody>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading