Search code examples
jquerytwitter-bootstrapbootstrap-4bootstrap-table

Bootstrap table won't sort


I am creating a bootstrap 4 table like this:

dataElement = $('<table id="' + questionID + 'table" data-toggle="table">');
dataElement.bootstrapTable({
    url: "api/eval/getAnswersToQuestion.php",
    method: "post",
    contentType: "application/x-www-form-urlencoded",
    queryParams: function(params){
        params["questionID"] = questionID;
        return params;
    },
    sortable: true,
    sortName: questionID,
    columns: [
        {
            field: 'token',
            title: 'Answer token'
        },
        {
            field: questionID,
            title: 'Answer',
            sortable: true
        }
    ]
});

It will sort the second column descending by default. However, it's not possible to click the table header in order to change the sorting order. What did I miss? In the corresponding example it's done like this.


Solution

  • The table has not been added to the DOM yet. You're creating a new table node in the first line of your snippet, and call the bootstrapTable on that node on the next line. Which is perfectly fine, the node will be displayed correctly, but it won't be interactive (e.g. sorting won't work).

    In order for the bootstrap table to work correctly, make sure the node is already existent in the DOM when the bootstrapTable method is called. This is because bootstrap table wants to transform the table node into the bootstrap table structure, which doesn't work outside the DOM.