Tips for utilizing sorting, searching, and pagination features in Bootstrap 5 tables

In my simple table,

https://i.sstatic.net/bu1md.png

Furthermore, I have integrated Bootstrap 5:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15777a7a61666167746555203b243b26">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91f3fefee5e2e5e3f0e1d1a4bfa0bfa2">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>

To achieve searching by values, selecting the number of visible rows, and sorting by columns,

I used to rely on $('#Table').bootstrapTable, but with version 5 it seems trickier to find examples for implementation.

Answer №1

I came to the realization that relying on pre-made solutions often involves a series of imports, including jquery. It's actually much simpler and more efficient to create your own code from scratch, which is exactly what I opted for

Here's a basic example with all class attributes removed for clarity. I've also included a value for the <td> tags, although it's not necessary if you don't have a complex nested structure (e.g. just a <td>value</td>)

<form>
    <input placeholder="Search" id="search-in-table" onkeypress="return event.keyCode != 13;">
</form>

<p>Show per page:</p>
<select id="form-select-coins">
    <option value="10" selected>10</option>
    <option value="20">20</option>
    <option value="30">30</option>
</select>

<table id="coins-table">

    <thead>

        <tr>
            <th>Name</th>
            <th>Holdings</th>
            <th>Price</th>
            <th>Avg. Buy Price</th>
            <th>Wallet Balance</th>
            <th>Profit/Loss</th>
        </tr>

    </thead>

    <tbody>

        <tr coin="COIN">
            <td value="COIN">COIN</td>
            <td value="TOTAL_COINS">TOTAL_COINS</td>
            <td value="CURRENT_PRICE">CURRENT_PRICE</td>
            <td value="AVG_BUY_PRICE">AVG_BUY_PRICE</td>
            <td value="WALLET_BALANCE">WALLET_BALANCE</td>
            <td value="PROFIT_LOSS">PROFIT_LOSS</td>
        </tr>

    </tbody>

</table>
function hide_table_elements(table_id, visible) {
    // Displays only the first `visible` table elements
    table_elements = document.getElementById(table_id).children[1].children

    for (const element of table_elements) {
        if (visible == 0) {
            element.style.display = 'none'
        }
        else {
            element.style.display = 'table-row'
            visible -= 1
        }
    }
}

// Use the following function for <td> without `value` attribute
// const getCellValue = (tr, idx) => tr.children[idx].innerText.replace('$', '') || tr.children[idx].textContent.replace('$', '');
const getCellValue = (tr, idx) => tr.children[idx].getAttribute('value')

const comparer = (idx, asc) => (a, b) =>
    ((v1, v2) => v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2))
    (getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx))

const reload_table = () => hide_table_elements('coins-table', document.getElementById('form-select-coins').value)

window.addEventListener('load', function () {   
    reload_table()

    // Show per page
    document.getElementById('form-select-coins').addEventListener('change', function() {
        counter = this.value
        hide_table_elements('coins-table', this.value)
    });

    // Search in table
    document.getElementById('search-in-table').addEventListener('input', function() {   
        rows = document.getElementById('coins-table').children[1].querySelectorAll('tr:nth-child(n)')
        value = this.value.toLowerCase()

        if (value == '')
            return reload_table()

        for (const row of rows) {
            if (row.getAttribute('coin').toLowerCase().includes(value)) {
                row.style.display = 'table-row'
            } else {
                row.style.display = 'none'
            }
        }       
    });

    // Sort table
    document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
        const table = document.getElementById('coins-table').children[1]

        Array.from(table.querySelectorAll('tr:nth-child(n)'))
            .sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
            .forEach(tr => table.appendChild(tr));
        
        reload_table()
    })));
});

Creating your own code is cost-effective and efficient. However, if you prefer using readymade solutions, you can explore options here

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

ASP.NET "Data" Error: Trouble Parsing JSON Data on the Front-End

I am currently facing an issue with the configurations on my asmx page. The code is set up like this: using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Script.Serialization; using Syst ...

Retrieve the Query String Information from a Link and Generate a New Link in Another List

I am looking to extract information from a link in #list and then use that information to create a new link in #list3. The link I have is http://jsfiddle.net/4y5V6/24/. Is there a way to set it up so that when a link is clicked, it automatically gets added ...

JavaScript and modifying the attributes of the nth child

I'm working on a navigation bar that changes the "background-image" of menu items using the nth-of-type CSS selector. Now, I need to figure out how to dynamically change the picture of the "background-image" when hovering over a specific menu item usi ...

Dynamic <figcaption> that adjusts to different screen sizes with smooth animations

My first WordPress theme is almost complete and I'm excited to share it: The responsive image grid on the homepage is giving me some trouble. When I shrink the browser window, the images don't scale properly. The grid works fine without the JS ( ...

Error encountered when processing a PUT request for a node causing a

After receiving minimal views and replies on a similar question I posted last night, I am reaching out again in hopes of resolving my issue. For the past two days, I have been struggling to fix this problem and progress with my project! If you are interes ...

"Unlocking the power of Node.js with a unique client

My iOS app is connected to a node.js backend that serves JSON data. I am looking for a way to implement client authentication for each app without requiring users to create an account. My goal is to uniquely identify each client app when accessing data and ...

``As I navigate through my react native app, I encounter the challenge of receiving the BackHandler

I've been developing a chat app and I'm trying to implement a feature where, upon clicking the default back button on Android, it both closes the keyboard and navigates back. Although I know how to capture the keyboard close event, I currently h ...

Creating a function that counts the number of times a button is clicked

I want to have the "game" button appear after the user clicks the "next-btn" 2 times. Once the multiple choice test has been completed twice, I'd like the game button to show up and redirect the user to a separate HTML page called "agario.html." I&ap ...

How can you determine if all specified events have been triggered in jQuery?

I am implementing custom triggered events following asynchronous calls, and I'm in need of a method to determine when all the events have been triggered. For instance: var ajaxCall1 = function(){ $.ajax({ url: "someUrl.html", com ...

Exploring how enums can be utilized to store categories in Angular applications

My application has enums for category names on both the back- and front-end: export enum CategoryEnum { All = 'All', Category1 = 'Category1', Category2 = 'Category2', Category3 = 'Category3', Cate ...

The kendo-grid-messages are utilized across all columns

I encountered an issue while working with the following code: <kendo-grid-column field="isActive" [title]="l('Status')" filter="boolean"> <kendo-grid-messages filterIsTrue="Yes" filterIsFalse=&qu ...

Combining Various Time Periods in JavaScript

After encountering various old solutions, most utilizing jQuery, for adding multiple durations together, I decided to create my own script below. While I may not be a JS expert, I am open to input on any potential issues with this code or a more efficient ...

Removing a row from a table with the click of a button

I recently wrote a piece of code to dynamically add or delete rows in an HTML table. The issue I'm facing is that while the addition of rows works perfectly fine, I'm unable to delete a specific row. Upon clicking the delete button, I encounter a ...

What causes jQuery results to resemble a function?

When I create a jQuery wrapped set and insert it into console.log, the output appears as follows: I am aware that we can manipulate the console to display objects or arrays. For example, when we have: var obj = { 0: 'some', 1: 'dat ...

When using the navbar in Tailwind CSS, the image is appearing distorted instead of aligning properly with the adjacent

I am trying to add a flag, login button, and sign up button Using class="flex", I placed an image inside it However, when I add the buttons, the image gets distorted. How can I prevent this? Expected Outcome I want to create the flag, login but ...

Develop a Vue component for a fixed sidebar navigation

I am in need of a vertical navigation bar positioned to the left of my app's layout, with the content extending across the right side. However, I am currently facing an issue where the navbar is pushing all the content downwards. How can I resolve thi ...

Step-by-step guide for sending data using module.exports in a node.js application

Currently, I am working on implementing a feature that will allow users to input data and store it in a database collection. The technologies I am using for this project are Node.js, MongoDB, Mongoose, Express.js, and AJAX. My goal is to capture user inpu ...

Tips for adding color to the <td> element in an ejs file using nodeJS

I am looking to incorporate a color into my .ejs file. Here is the code snippet I am working with: <% resultList.forEach(function(item, index){ %> <tr> <td><%= item.function %></td> <td><%= item.value %>< ...

Extracting live TV channels from an m3u file by differentiating them from VOD content

Currently, I am developing an IPTV player app and have successfully parsed the m3u file. My current challenge is separating live TV channels from Video on Demand (VOD). I am unsure of where exactly the transition happens in the playlists. Below are the ke ...

Utilizing a Chrome packaged app to interact with a local sqlite database through reading and writing operations

Is it feasible to access and manipulate a local sqlite database from within a Chrome packaged app? I am currently able to work with a locally stored JSON file for my app data, but now I also require the functionality to interact with a sqlite database in ...