Search code examples
javascriptjquerysortinggeolocation

Sorting table rows by a column


I have a list of cities with calculated distances using geolocation API in a table. I want to automatically sort the table rows by the distance column. I have tried several table sort plugin but all of them failed.

Any suggestion? here is my code: jsfiddle.net/vLLsLLrb/

Here's how the table looks:

enter image description here


Solution

  • To do it quickly, I used sorttable.js by following these steps:

    • include sorttable.js
    • add class "sortable" to your table
    • remove "km" from numbers (you can add them again later, using css:after)

    Basically, mainly changing your table tag:

            <table id="nearest" class="table table-striped sortable">
                <thead>
                    <tr>
                        <th>Destination</th>
                        <th>Distance to</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th>London</th>
                        <td><span id='london'></span>
                        </td>
                    </tr>
                    <tr>
                        <th>Newcastle</th>
                        <td><span id='newcastle'></span>
                        </td>
                    </tr>
                    <tr>
                        <th>Cardiff</th>
                        <td><span id='cardiff'></span>
                        </td>
                    </tr>
                    <tr>
                        <th>Cambridge</th>
                        <td><span id='cambridge'></span>
                        </td>
                    </tr>
                    <tr>
                        <th>Reading</th>
                        <td><span id='reading'></span>
                        </td>
                    </tr>
                </tbody>
            </table>
    

    That's it, now your distance column has a sorting triangle besides it! Here's the jsfiddle!