Search code examples
javascriptbootstrap-4bootstrap-table

Bootstrap table numeric sort of an ID table


I'm using the Boostrap table for the depiction of the table from my DB in my admin page. I save an array into json file then I get to the table and show it with the following code:

<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'>Добавить запись</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\" >Заголовок</th>
                            <th data-field=\"intro\" data-sortable=\"true\" >Введение</th>
                            <th data-field=\"status\" data-sortable=\"true\" >Статус</th>
                            <th data-field=\"seo\" data-sortable=\"true\" >Сео</th>
                            <th data-field=\"type\" data-sortable=\"true\" >Тип</th>
                            <th data-field=\"date\" data-sortable=\"true\" >Дата</th>
                                                            
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>

The problem is that Bootstrap table is sorting only alphanumerically, i.e. (1,11,12,2,21,3) etc. Have you had any experience in making Bootstrap tables forcing into numeric sort, i.e.(1,2,3,11,12,21)?


Solution

  • In the newest version of the Bootstrap tables, I found following.

    You can use

    data-custom-sort="customSort"
    

    Then you need to put the following script right below the HTML of the table used.

    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
        })
    }