Sorting numeric ID columns in a Bootstrap table

I've implemented the Boostrap table to display data from my database on my admin page. I saved an array into a json file, and then used the following code to populate the table:

<div class=\"row\">
        <div class=\"col-lg-12\">
            <div class=\"panel panel-default\">
                <div class=\"panel-heading\"> <a href='record_show.php?tselect=blog&typerec=newblog' class='btn btn-success'>Add Record</a></div>
                
         <table data-toggle=\"table\" data-url=\"tables/data4.json\"  data-sort-name=\"id\" data-sort-order=\"desc\" data-show-refresh=\"true\" data-show-toggle=\"true\" data-show-columns=\"true\" data-search=\"true\" data-select-item-name=\"toolbar1\" data-pagination=\"true\" >

                        <thead>
                        <tr>
                            <th data-field=\"id\" data-sortable=\"true\">ID</th>
                            <th data-field=\"header\" data-sortable=\"true\" >Header</th>
                            <th data-field=\"intro\" data-sortable=\"true\" >Introduction</th>
                            <th data-field=\"status\" data-sortable=\"true\" >Status</th>
                            <th data-field=\"seo\" data-sortable=\"true\" >SEO</th>
                            <th data-field=\"type\" data-sortable=\"true\" >Type</th>
                            <th data-field=\"date\" data-sortable=\"true\" >Date</th>
                                                            
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>

The issue is that the Bootstrap table only sorts alphanumerically, for example (1,11,12,2,21,3) instead of numerically (1,2,3,11,12,21). Have you encountered this problem before? If so, how did you make the Bootstrap tables sort numerically?

Answer №1

Within the latest iteration of Bootstrap tables, I stumbled upon an interesting feature.

You have the ability to implement

data-custom-sort="customSort"

After adding this line, make sure to include the following script directly beneath the table's HTML code.

function customSort(sortName, sortOrder, data) {
    var order = sortOrder === 'desc' ? -1 : 1
    data.sort(function (a, b) {
        var aa = +((a[sortName] + '').replace(/[^\d]/g, ''))
        var bb = +((b[sortName] + '').replace(/[^\d]/g, ''))
        if (aa < bb) {
            return order * -1
        }
        if (aa > bb) {
            return order
        }
        return 0
    })
}

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

Tips for automating the activation of intents at specific scheduled times in Dialogflow

I'm attempting to automatically trigger intents in Dialogflow to obtain the user's contact details at a scheduled time. Is it possible to achieve this using JavaScript? If so, could you please provide the code? ...

Troubleshooting: Vue.js file upload encountering OPTIONS 404 error

In my express app, I have configured CORS and most of the routes are working fine. However, I'm facing an issue with a specific component used for uploading images: <input type="file" class="form-control" @change="imageChanged"> <div @clic ...

Implement the same reference functionality in a React Function component that is seen in a React Class component

Is it possible to replicate the same functionality of class component ref in a function component? Here's an example: const AnotherComponent = () => { const DoSomething = () => console.log(something); return <div> There is some co ...

Explain the functioning of the Node.js event loop and its ability to manage numerous requests simultaneously

Recently, I delved into testing asynchronous code in node.js. From what I understand, when there is an asynchronous operation taking place, Node.js should be able to handle new requests. Below is a snippet of code I wrote using express and axios: app.get(& ...

Issue with Fancybox and Jquery compatibility

I'm encountering some issues with conflicting Javascripts. One script is responsible for creating a dropdown menu, while another set of scripts enable fancybox functionality. However, having both sets of scripts in the header code results in conflicts ...

Utilizing Node Js for Form Data Transmission and Retrieval

I've successfully created two separate JS files, each responsible for sending and retrieving form data to and from the database. My dilemma is whether it's more practical or feasible to leave these two JS files as they are and serve their individ ...

Having trouble with data retrieval from MySQL using PHP and Angular on certain mobile devices, although it functions properly on desktops and laptops

The data retrieved from the mysql database is functioning properly on desktop and laptop, but not on mobile devices. The following HTML code is present in the html file: <table class="table table-default"> <thead> <tr> & ...

The priority of custom attributes in HTML

There seems to be some ambiguity regarding whether data- attributes should be considered primary or secondary syntax. Is there a defined standard for this in major frameworks like Angular? For example, if an attribute is specified as both my-attr and dat ...

POST request body is not defined

Client Interface: procedure OnButtonClick(Sender: TObject); begin gcm := GetGCMInstance; p := TJavaObjectArray<JString>.Create(1); p.Items[0] := StringToJString('460004329921'); FRegistrationID := JStringToString(gcm.register(p)); ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

Conceal part of the page initially, then reveal it when clicked

After integrating Rails 3 and JQuery, I encountered an issue where a div containing a rendered partial would not hide when attempting to do so using JQuery in my JavaScript. I want to be able to hide the div initially, then show it upon clicking a button. ...

Monitor changes in the visible price range in lightweight-chart

Is there a way to detect when the visible price range changes in lightweight-chart, similar to how the timeScale's visible time range change can be detected through subscribeVisibleTimeRangeChange? I couldn't find anything related in the document ...

Develop a Rails object using AJAX and JavaScript

Within a music application built on Rails, I am attempting to monitor plays for tracks by artists. This involves creating a unique play object each time a visitor plays a track on the site. These play objects are assigned their own distinct IDs and are ass ...

Tips for leveraging async and await within actions on google and API integration

Currently, I am developing an Actions on Google project that utilizes an API. To handle the API calls, I am using request promise for implementation. Upon testing the API call, I observed that it takes approximately 0.5 seconds to retrieve the data. Theref ...

Opening a modal in Bootstrap 4 selectpicker depending on the chosen value

I am facing an issue with a selectpicker that has live search functionality. I want to trigger a modal to open only when the user clicks on the option that says "Add new contractor." However, this modal is currently opening for all options, even though I o ...

saving the hash key in a separate array

Currently, I have a collection of key-value pairs that need to be stored in another array. However, I am facing difficulties with the logic as I am unable to keep track of which keys-values have already been assigned while iterating over the list of object ...

The palindrome checking function is malfunctioning and needs to be fixed

I have attempted to create a function to determine if a number is a palindrome, but it seems to be malfunctioning. The concept is simple - splitting the number into two halves, comparing them, and reversing one half to check for symmetry. function palin ...

Effortlessly move and release Internet Explorer

Encountering drag and drop issues in Internet Explorer and Safari, while functioning correctly in Firefox 15 (untested on other versions). Dragging and dropping items between dropzones works in Safari, but sorting does not. In Internet Explorer, nothing wo ...

Material-UI slider in React keeps reverting back to zero value

Exploring the construction of an interface where selecting a radio option reveals distinct form elements. Once a slider is exposed, any value changes are stored in an object that is subsequently visible on the page. In this scenario, the object does get ...

What is the best way to organize and sort mysql data without disrupting operations?

I've been searching for information on this topic but haven't been able to find a tutorial that explains exactly what program to use. I have a MySQL database with expenses data. What I need is for the system to automatically categorize a new ex ...