I need to sort my <table>
by grouped multiple <tbody>
's
It's pretty straight forward and looks like this:
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody class="listing-1">
<tr>
<td>Blue widget</td>
<td>1</td>
</tr>
<tr>
<td colspan="2">text</td>
</tr>
</tbody>
<tbody class="listing-2">
<tr>
<td>Red Widget</td>
<td>2</td>
</tr>
<tr>
<td colspan="2">text</td>
</tr>
</tbody>
<tbody class="listing-3">
<tr>
<td>Blue widget</td>
<td>3</td>
</tr>
<tr>
<td colspan="2">text</td>
</tr>
</tbody>
</table>
I'm grouping each listing in a <tbody>
and want to sort the table having the two <tr>
's in each <tbody>
locked together.
If I sort by the Header 1 to get the <td>
's with Blue widget on top, I need the whole of each <tbody>
to move up, so it looks like:
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody class="listing-1">
<tr>
<td>Blue widget</td>
<td>1</td>
</tr>
<tr>
<td colspan="2">text</td>
</tr>
</tbody>
<tbody class="listing-3">
<tr>
<td>Blue widget</td>
<td>3</td>
</tr>
<tr>
<td colspan="2">text</td>
</tr>
</tbody>
<tbody class="listing-2">
<tr>
<td>Red Widget</td>
<td>2</td>
</tr>
<tr>
<td colspan="2">text</td>
</tr>
</tbody>
</table>
I've been using ListJS (http://listjs.com/) to sort my tables, but it doesn't appear to support grouping tbody's like this. I then checked out TableSorter (https://mottie.github.io/tablesorter/), but that doesn't appear to support it either.
I am at a loss on how to sort this, but I'm thinking I can't be the only one ever wanting to do something like this. Maybe I'm asking the wrong question?
Any help or suggestion on how to do this, or which plugin to use, would be really awesome.
EDIT: Criteria for sorting is the first of each in each . The second in each need to be locked together with the first in each, and not sortable. So the second is not ever supposed to be sortable, but instead should be locked in with the first .
Let me know if I'm still not making myself clear, and I'll try again.
it's not very clear what the sort criteria is. Assuming it is the number in second cell can do something like:
var $tBodies = $('tbody').sort(function(a, b){
var aVal = +($(a).find('tr:first td').eq(1).text().trim() || 0);
var bVal = +($(b).find('tr:first td').eq(1).text().trim() || 0);
return aVal - bVal;
});
$('table').append($tBodies);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody class="listing-1">
<tr>
<td>Blue widget</td>
<td>1</td>
</tr>
<tr>
<td colspan="2">text</td>
</tr>
</tbody>
<tbody class="listing-3">
<tr>
<td>Blue widget</td>
<td>3</td>
</tr>
<tr>
<td colspan="2">text</td>
</tr>
</tbody>
<tbody class="listing-2">
<tr>
<td>Red Widget</td>
<td>2</td>
</tr>
<tr>
<td colspan="2">text</td>
</tr>
</tbody>
</table>