0
How can I sort the following table using Javascript? How can I do a function that chooses the column to be ordered ascending or descending?
<table border="1">
<tr><td>a</td><td>s</td></tr>
<tr><td>d</td><td>r</td></tr>
<tr><td>c</td><td>t</td></tr>
<tr><td>f</td><td>q</td></tr>
<tr><td>b</td><td>k</td></tr>
<tr><td>e</td><td>o</td></tr>
<tr><td>l</td><td>p</td></tr>
<tr><td>k</td><td>d</td></tr>
<tr><td>j</td><td>c</td></tr>
<tr><td>i</td><td>z</td></tr>
<tr><td>h</td><td>b</td></tr>
<tr><td>q</td><td>l</td></tr>
<tr><td>p</td><td>m</td></tr>
<tr><td>o</td><td>n</td></tr>
<tr><td>n</td><td>a</td></tr>
<tr><td>g</td><td>f</td></tr>
<tr><td>x</td><td>g</td></tr>
<tr><td>m</td><td>e</td></tr>
<tr><td>u</td><td>j</td></tr>
<tr><td>t</td><td>i</td></tr>
<tr><td>w</td><td>y</td></tr>
<tr><td>s</td><td>h</td></tr>
<tr><td>v</td><td>u</td></tr>
<tr><td>r</td><td>v</td></tr>
<tr><td>y</td><td>w</td></tr>
<tr><td>z</td><td>x</td></tr>
</table>
I’ve already tried this: I’m using jQuery 3.4.1 in case of questions
sort_table(document.getElementsByTagName('table'), 'asc', 0)
function sort_table(table:any, order:string, column:number) {
var tbody = $(table.target).find('tbody')
tbody.find('tr').sort(function(a, b) {
if (order !== 'asc') {
return $('td:'+column+'', a).text().localeCompare($('td:'+column+'', b).text());
} else {
return $('td:'+column+'', b).text().localeCompare($('td:'+column+'', a).text());
}
}).appendTo(tbody)
}
Can anyone help sort this table?
Hello thank you so much for the answer is working perfectly, has how to do so, but calling a function for example Function sortTable(table, 'asc or desc', column number) instead of clicking?
– Isaac
Look at the editing, I made the adjustment.
– Taffarel Xavier
I will add a button (in case you want to organize by clicking a button) here and initialize it already organized too.
– Taffarel Xavier