最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sorting rows in the table as we click on the table header - Stack Overflow

programmeradmin0浏览0评论

I have a task of sorting the table row in a table. The data in the table is a mixture of everything like date, number, string etc etc.

I have gone through many links where I found some are directed to the ready library. Which is of no use to me. Finally going through lot of things I have made my own using all tits and bits. which is working only for number

This is the script:

  $(document).ready(function () {

        //grab all header rows
        $('th').each(function (column) {
            $(this).addClass('sortable').click(function () {
                    var findSortKey = function ($cell) {
                        return $cell.find('.sort-key').text().toUpperCase()+ ' ' + $cell.text().toUpperCase();

                    };
                    var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;
                    var $rows = $(this).parent().parent().parent().find('tbody tr').get();

                    //loop through all the rows and find
                    $.each($rows, function (index, row) {
                        row.sortKey = findSortKey($(row).children('td').eq(column));
                    });

                    //pare and sort the rows alphabetically or numerically
                    $rows.sort(function (a, b) {
                        if (a.sortKey.indexOf('-') == -1) {
                            if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
                                return -sortDirection;
                            }
                            if (parseInt(a.sortKey) > parseInt(b.sortKey)) {                                
                                return sortDirection;
                            }
                        } else {
                            if (a.sortKey < b.sortKey) {
                                return -sortDirection;
                            }
                            if (a.sortKey > b.sortKey) {
                                return sortDirection;
                            }
                        }
                        return 0;
                    });

                    //add the rows in the correct order to the bottom of the table
                    $.each($rows, function (index, row) {
                        $('tbody').append(row);
                        row.sortKey = null;
                    });

                    //identify the column sort order
                    $('th').removeClass('sorted-asc sorted-desc');
                    var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');
                    sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');

                    //identify the column to be sorted by
                    $('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
                });
            });
        });

This is the style for the document:

    <style>
    root
    {
        display: block;
    }

    th.sortable
    {
        color: #666;
        cursor: pointer;
        text-decoration: underline;
    }

        th.sortable:hover
        {
            color: black;
        }

    th.sorted-asc, th.sorted-desc
    {
        color: black;
        background-color: cadetblue;
    }
</style>

So below is the HTML part.

<table>
    <tbody>
        <tr>
            <th class="sortable">Name</th>
            <th class="sortable">Salary</th>
            <th>Extension</th>
            <th>Start date</th>
            <th>Start date (American)</th>
        </tr>
        <tr>
            <td>Bloggs, Fred</td>
            <td>$12000.00</td>
            <td>1353</td>
            <td>18/08/2003</td>
            <td>08/18/2003</td>
        </tr>
        <tr>
            <td>Turvey, Kevin</td>
            <td>$191200.00</td>
            <td>2342</td>
            <td>02/05/1979</td>
            <td>05/02/1979</td>
        </tr>
        <tr>
            <td>Mbogo, Arnold</td>
            <td>$32010.12</td>
            <td>2755</td>
            <td>09/08/1998</td>
            <td>08/09/1998</td>
        </tr>
        <tr>
            <td>Shakespeare, Bill</td>
            <td>$122000.00</td>
            <td>3211</td>
            <td>12/11/1961</td>
            <td>11/12/1961</td>
        </tr>
        <tr>
            <td>Shakespeare, Hamnet</td>
            <td>$9000</td>
            <td>9005</td>
            <td>01/01/2002</td>
            <td>01/01/2002</td>
        </tr>
        <tr>
            <td>Fitz, Marvin</td>
            <td>$3300</td>
            <td>5554</td>
            <td>22/05/1995</td>
            <td>05/22/1995</td>
        </tr>
    </tbody>
</table>

I have a task of sorting the table row in a table. The data in the table is a mixture of everything like date, number, string etc etc.

I have gone through many links where I found some are directed to the ready library. Which is of no use to me. Finally going through lot of things I have made my own using all tits and bits. which is working only for number

This is the script:

  $(document).ready(function () {

        //grab all header rows
        $('th').each(function (column) {
            $(this).addClass('sortable').click(function () {
                    var findSortKey = function ($cell) {
                        return $cell.find('.sort-key').text().toUpperCase()+ ' ' + $cell.text().toUpperCase();

                    };
                    var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;
                    var $rows = $(this).parent().parent().parent().find('tbody tr').get();

                    //loop through all the rows and find
                    $.each($rows, function (index, row) {
                        row.sortKey = findSortKey($(row).children('td').eq(column));
                    });

                    //pare and sort the rows alphabetically or numerically
                    $rows.sort(function (a, b) {
                        if (a.sortKey.indexOf('-') == -1) {
                            if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
                                return -sortDirection;
                            }
                            if (parseInt(a.sortKey) > parseInt(b.sortKey)) {                                
                                return sortDirection;
                            }
                        } else {
                            if (a.sortKey < b.sortKey) {
                                return -sortDirection;
                            }
                            if (a.sortKey > b.sortKey) {
                                return sortDirection;
                            }
                        }
                        return 0;
                    });

                    //add the rows in the correct order to the bottom of the table
                    $.each($rows, function (index, row) {
                        $('tbody').append(row);
                        row.sortKey = null;
                    });

                    //identify the column sort order
                    $('th').removeClass('sorted-asc sorted-desc');
                    var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');
                    sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');

                    //identify the column to be sorted by
                    $('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
                });
            });
        });

This is the style for the document:

    <style>
    root
    {
        display: block;
    }

    th.sortable
    {
        color: #666;
        cursor: pointer;
        text-decoration: underline;
    }

        th.sortable:hover
        {
            color: black;
        }

    th.sorted-asc, th.sorted-desc
    {
        color: black;
        background-color: cadetblue;
    }
</style>

So below is the HTML part.

<table>
    <tbody>
        <tr>
            <th class="sortable">Name</th>
            <th class="sortable">Salary</th>
            <th>Extension</th>
            <th>Start date</th>
            <th>Start date (American)</th>
        </tr>
        <tr>
            <td>Bloggs, Fred</td>
            <td>$12000.00</td>
            <td>1353</td>
            <td>18/08/2003</td>
            <td>08/18/2003</td>
        </tr>
        <tr>
            <td>Turvey, Kevin</td>
            <td>$191200.00</td>
            <td>2342</td>
            <td>02/05/1979</td>
            <td>05/02/1979</td>
        </tr>
        <tr>
            <td>Mbogo, Arnold</td>
            <td>$32010.12</td>
            <td>2755</td>
            <td>09/08/1998</td>
            <td>08/09/1998</td>
        </tr>
        <tr>
            <td>Shakespeare, Bill</td>
            <td>$122000.00</td>
            <td>3211</td>
            <td>12/11/1961</td>
            <td>11/12/1961</td>
        </tr>
        <tr>
            <td>Shakespeare, Hamnet</td>
            <td>$9000</td>
            <td>9005</td>
            <td>01/01/2002</td>
            <td>01/01/2002</td>
        </tr>
        <tr>
            <td>Fitz, Marvin</td>
            <td>$3300</td>
            <td>5554</td>
            <td>22/05/1995</td>
            <td>05/22/1995</td>
        </tr>
    </tbody>
</table>
Share Improve this question edited Feb 13, 2016 at 15:16 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Aug 30, 2012 at 5:00 teenuteenu 7042 gold badges8 silver badges24 bronze badges 3
  • Here's a fiddle if any one wants to fork it jsfiddle/jZ6zZ – andrewk Commented Aug 30, 2012 at 5:10
  • I have used tablesorter./docs extensively in the past. Have you checked it out? If so how does it not meet your needs? – Jon P Commented Aug 30, 2012 at 5:14
  • Hi @JonP, The problem is it uses Lib from its site "jquery.tablesorter.js" which is not allowed. I need to write the code or frame it by my own. So only option is to edit my own code. – teenu Commented Aug 30, 2012 at 5:18
Add a ment  | 

1 Answer 1

Reset to default 3

Sounds like homework, which is fine, as you have shown some effort yourself. If you are not allowed to tablesorter , download it, I think there is a debug version, and have a look at the code. That should help you in your quest.

If this is homework, remember out in the real world that a golden rule of programming is don't re-invent the wheel. If there is a plug in that meets your needs, use it.

Fixing What you have

The problem with your code as it stands is:

if (a.sortKey.indexOf('-') == -1) {
    if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
        return -sortDirection;
     }

     if (parseInt(a.sortKey) > parseInt(b.sortKey)) {                                
          return sortDirection;
     }
} else {
    //Non numeric sort
}

Here you are always trying to sort as an integer if a does not contain -. A very rough fix is:

if (a.sortKey.indexOf('-') == -1 && (!isNaN(a.sortKey) && !isNaN(a.sortKey))) {
//Rough Numeracy check                          

    if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
        return -sortDirection;
    }

    if (parseInt(a.sortKey) > parseInt(b.sortKey)) {                                
        return sortDirection;
    }

 } else {
    //Non numeric sort
 }

Here is a working fidle.

Keep in mind this is a very rough numeracy check you will probably need other checks and balances for other data types.

发布评论

评论列表(0)

  1. 暂无评论