I am seeking assistance with a table I created that has multiple tabs containing different data. Each tab displays different information within the table rows, including a column for the number of votes. I am looking to automatically sort the rows based on the number of votes, with the highest vote counts appearing at the top.
Below is my HTML code:
<div class="row" style="text-align: center;">
<div class="container" style="margin-top: 8%;">
<ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="pills-comedy-tab" data-bs-toggle="pill" data-bs-target="#pills-comedy" type="button" role="tab" aria-controls="pills-comedy" aria-selected="false">COMEDY MOVIES</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="pills-horror-tab" data-bs-toggle="pill" data-bs-target="#pills-horror" type="button" role="tab" aria-controls="pills-horror" aria-selected="false">HORROR MOVIES</button>
</li>
</ul>
<div class="tab-content" id="pills-tabContent">
<!--START OF COMEDY MOVIES TAB-->
<div class="tab-pane fade show active" id="pills-comedy" role="tabpanel" aria-labelledby="pills-comedy-tab">
<table class="table">
<thead>
<tr>
...
</tr>
</thead>
<tbody>
<tr>
...
</tr>
...
</tbody>
</table>
</div>
<!--END OF COMEDY MOVIES TAB-->
<!--START OF HORROR MOVIES TAB-->
<div class="tab-pane fade" id="pills-horror" role="tabpanel" aria-labelledby="pills-horror-tab">
<table class="table">
<thead>
<tr>
...
</thead>
<tbody>
<tr>
...
</tr>
...
</tbody>
</table>
</div>
<!--END OF HORROR MOVIES TAB-->
</div>
</div>
</div>
</div>
This is the JavaScript code I am utilizing to sort by the vote column
$(document).ready(function(e) {
var dataRows = [];
//Create an array of all rows with its value (this assumes that the amount is always a number. You should add error checking!! Also assumes that all rows are data rows, and that there are no header rows. Adjust selector appropriately.
$('tr').each(function(i, j) {
dataRows.push({ 'vote': parseFloat($(this).find('.vote').text()), 'row': $(this) });
})
//Sort the data smallest to largest
dataRows.sort(function(a, b) {
return b.vote - a.vote;
});
//Remove existing table rows. This assumes that everything should be deleted, adjust selector if needed :).
$('table').empty();
//Add rows back to table in the correct order.
dataRows.forEach(function(ele) {
$('table').append(ele.row);
})
});
After running this code, I noticed that it sorts the columns but also relocates the table from the HORROR TAB to the COMEDY TAB, creating duplicates. When I remove the tabs, the sorting works fine. There seems to be a conflict with the tabs impacting the sorting process, and I am struggling to identify the issue.
I would greatly appreciate any guidance as I have been trying to resolve this for days. Thank you.