Search code examples
htmlbootstrap-table

Showing the index of a row in a bootstrap table


I want to be able to display the index of the respective row in a bootstrap table. My table looks like the following:

<div class="Explorer" style="display:none">
<table class='table'>
    <thead>
        <tr>
            <th>Rank</th>
            <th>Username</th>
            <th>Points</th>
        </tr>
    </thead>
{% for instance in leaderboardDictionaries %}
    {% for category, userDictionary in instance.items %}
        {% if category == "Explorer" %}
            <tr><td> {{category}} </td></tr>
            {% for name, points in userDictionary.items %}
                <tr>
                    <td data-formatter="runningFormatter" data-field="index">HERE I WANT THE INDEX OF THE ROW?!</td>
                    <td>{{name}}</td>
                    <td>{{points}}</td>
                </tr>
            {% endfor %}
        {% endif %}
    {% endfor %}
{% endfor %}
</table>
</div>

I looked in the web and found this but I can't make it work in any useful way....So the suggestion is to make an external function:

<script>
function runningFormatter(value, row, index) {
return index+1;
}
</script>

Nevertheless how should I use this? The function already takes the row and the index as an argument. And I wonder why there is no 'format-option' for a table, such that i simply displays the row index by default --- or is there?


Solution

  • You need to put the data- attributes in the <th> elements, not the <td> elements as they are column-level attributes.

    <th data-formatter="runningFormatter">Rank</th>

    Second, data-field is used to map the data from an javascript array or an external source to your columns. You don't need that since you are writing the table in html.

    The index will return the row index based on the displayed data.