How can I order a table like this:
Group pos
b 2
c 1
b 1
a 1
to this:
Group pos
a 1
b 1
b 2
c 1
with jquery?
The table should not be sortable .
I only want to sort the rows once and I would like to order two columns.
You can use sort()
to sort the table
$('tbody tr').sort(function(a, b) { var td1 = $(a).find('td'), td2 = $(b).find('td'); // condition for sort - compare with first column if they are equal then compare with second column return (td1.eq(0).text() > td2.eq(0).text() || (td1.eq(0).text() == td2.eq(0).text() && td1.eq(1).text() > td2.eq(1).text())) || 0; }).appendTo('table tbody');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <thead> <tr> <th> Group</th> <th>pos</th> <tr> </thead> <tbody> <tr> <td> b </td> <td>2</td> </tr> <tr> <td> c </td> <td>1</td> </tr> <tr> <td> b </td> <td>1</td> </tr> <tr> <td> a </td> <td>1</td> </tr> </tbody> </table>
Or
$('tbody tr').sort(function(a, b) { var td1 = $(a).find('td'), td2 = $(b).find('td'); // condition for sort - compare with first column if they are equal then compare with second column if (td1.eq(0).text() > td2.eq(0).text() || (td1.eq(0).text() == td2.eq(0).text() && td1.eq(1).text() > td2.eq(1).text())) return 1; else if (td1.eq(0).text() < td2.eq(0).text() || (td1.eq(0).text() == td2.eq(0).text() && td1.eq(1).text() < td2.eq(1).text())) return -1; return 0; }).appendTo('table tbody');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <thead> <tr> <th> Group</th> <th>pos</th> <tr> </thead> <tbody> <tr> <td> b </td> <td>2</td> </tr> <tr> <td> c </td> <td>1</td> </tr> <tr> <td> b </td> <td>1</td> </tr> <tr> <td> a </td> <td>1</td> </tr> </tbody> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.