Arranging Data in a Table using Tabs and JavaScript

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.

Answer №1

My solution involved creating separate arrays for each tab (comedy and horror), allowing for a more organized approach. By duplicating the JavaScript functions and using specific selectors, I was able to efficiently handle the data.

var dataRows1 = []
var dataRows2 = []
function sortRows() {

    //Create an array of all rows with their values
    $('#pills-comedy tr').each(function () {
        dataRows1.push({
            'vote': parseFloat($(this).find('.vote').text()),
            'row': $(this)
        });
    })
    $('#pills-horror tr').each(function () {
        dataRows2.push({
            'vote': parseFloat($(this).find('.vote').text()),
            'row': $(this)
        });
    })

    //Sort the data from smallest to largest
    dataRows1.sort(function (a, b) {
        return b.vote - a.vote;
    });
    dataRows2.sort(function (a, b) {
        return b.vote - a.vote;
    });

    //Remove existing table rows
    $('#pills-comedy table').empty();
    $('#pills-horror table').empty();

    //Add rows back to the table in the correct order
    dataRows1.forEach(function (ele) {
        $('#pills-comedy table').append(ele.row);
    })
    dataRows2.forEach(function (ele) {
        $('#pills-horror table').append(ele.row);
    })
};

While this method achieved the desired outcome, it did cause some unexpected layout issues within the Bootstrap framework. Further investigation is needed to address these issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue.js computed property experiencing a minor setback

I'm currently working on developing a test-taking system using Vue and Laravel. When a user inputs the test code and email address, they are directed to the test page. To display all the test questions based on the entered code, I implemented a naviga ...

React.js: Passing an array as a property to an element results in the transformation of the array into an object

I'm trying to understand why passing an array as a prop to another element results in it getting transformed into an object with the array as its value. I need help understanding if this is a common JavaScript 'quirk' or specific to React an ...

Guide on converting JSON data into a PDF using TypeScript

I need to take JSON data and convert it into a PDF format when the PDF button is clicked in the UI. I have tried a few things but I'm struggling with binding the response to the PDF function. My goal is to display values from the "actualExpenses" arra ...

After submitting the form, React checkboxes fail to reset their state

Being a relative newcomer to React, I embarked on creating a skincare app as a project to enhance my understanding. In designing the app, I incorporated a form for product registration which includes checkboxes. My current dilemma revolves around clearing ...

What is the reason `addEventListener` does not work with a class method?

Recently, I discovered that the listener passed to addEventListener can actually be an object with a handleEvent function instead of just a callback function (here). However, I encountered an issue when trying to use handleEvent as a class method: class F ...

Unable to See Success Notification on First Attempt

I am facing an issue with displaying a message when adding a new record. The first time I add a record, the message shows up correctly. However, if I try to add another record, the message does not appear even though the record is added successfully. Here ...

What is the best way to select the initial element from my class within my component using protractor?

Can anyone help me figure out how to click on the button in this component? I need guidance on navigating through the following path: Is xpath my only option for doing this? I believe a css locator could work as well, but I am unsure of how to construct ...

Providing parameters to a dynamic component within NextJS

I am dynamically importing a map component using Next.js and I need to pass data to it through props. const MapWithNoSSR = dynamic(() => import("../Map"), { ssr: false, loading: () => <p>...</p>, }); Can anyone sugges ...

Having trouble with sending a list of items from a VueJS form

I have a VueJS application that calls a patch method to update a user's profile. For example, I am attempting to update the field cities. I created a serializer and views.py using Postman during development. I used Postman to call the patch method fo ...

Callback in React Setstate triggered, leading to a delay in rendering

Recently, I embarked on a journey to learn React just 2 days ago. Despite my enthusiasm, I have encountered some challenges with React's setState method. As far as my understanding goes, I should utilize the prevState parameter when I need to alter th ...

When using Next JS with StoryBook, an error may occur if styles are written in a module.scss file

Every time I try to add some styles to my ButtonWidget.scss file, I encounter an error in the console when running the command yarn storybook Error Code: ERROR in ./src/components/ButtonWidget/ButtonWidget.module.scss 1:0 Module parse failed: Unexpected ...

Error: Attempting to access property 'question' of an undefined value

Trying to render information from a local .json file using Javascript functions, I encountered an error in the console for const answer despite being defined. I temporarily commented it out to test the function, only to receive the same TypeError for quest ...

Unable to render dynamic ID in Next.js version 13.4.6 due to an issue

https://i.sstatic.net/x8oF1.pnghttps://i.sstatic.net/OEIL5.png Currently diving into next-js! Previously, I utilized dynamic id rendering in my projects. However, encountering errors now with the current version (next js 13.4.6). Having trouble identifyin ...

Choose information based on the prior choice made

Using the Material UI Stepper, I have a task that involves setting conditions based on the selection of checkboxes. In step one, there are two checkboxes - Individual and Bulk. In step two, there are also two checkboxes - First Screening and Second Screeni ...

How to obtain the value of TR in JavaScript?

Objective: Extract the value "2TR" from "MARSSTANDGATA132TR" using JavaScript. Need to determine the location of the digit 2 within the extracted string. Issue: Uncertain about the correct syntax to achieve this task. Additional Details: *The cha ...

unable to retrieve JSON sub-elements

I encountered an issue while attempting to iterate through the JSON object provided. When trying to access the content-items using page.content-items, I received an error message. Is it possible to access an object that has a key with "-" in its name? Co ...

Using the JavaScript JSX syntax, apply the map function to the result of a

My aim is to create a structure resembling the following: <td> {phones.map((phone, j) => <p>{this.renderPhone(phone)}</p> )} </td> However, there may be instances where the phones array is not defined. Is it feas ...

Is there a way to deactivate all dot inputs on number type input in vue.js 2?

Here is an example of my HTML code: <div id="app"> <input type="number" v-model="quantity"/> </div> This is how my Vue component looks: new Vue({ el: '#app', data: { quantity: '' }, watch: { quanti ...

jQuery unable to find designated elements in uploaded templates

I have a specific route linked to a specific controller and view: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/create', { templateUrl: 'partials/form/form.html', controlle ...

TypeError: "Table" has not been declared

This is my first experience with the script editor. I have been given the task of creating a pivot table for Google Sheets using a script. // This script creates a pivot table in Google Sheets function createPivotTable() { var ss = SpreadsheetApp.getAc ...