Skip to main content

How to Sort Data of HTML Table Column using jQuery Tutorial

Screenshot
Body

In this tutorial, we will tackle about how to Sort the HTML Table Column Data using jQuery. Here, I will show how to create a custom JavaScript function that can sort each column in your HTML table. I will be providing a simple HTML Application Source code below which contains a sample HTML Table with Table sorting function. The sorting function will be triggered when the user clicks the column header. Each column header will have an arrow up icon if a user triggers the column to sort in ascending direction and an arrow down for descending direction.

Getting Started

In this tutorial, I used Bootstrap v5 for the design of application. And, kindly download also the jQuery Library. After that, compile you CSS and Script assets into a directory.

Creating the Interface

The script below the is the code for our Page Interface. This contains the table scripts. Save the script below as index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Table Sorting in PHP and jQuery</title>
  8. <link rel="stylesheet" href="./css/bootstrap.min.css">
  9. <!-- Custom CSS -->
  10. <script src="./js/jquery-3.6.0.min.js"></script>
  11. <script src="./js/bootstrap.min.js"></script>
  12. <script src="./js/script.js"></script>
  13. :root {
  14. --bs-success-rgb: 71, 222, 152 !important;
  15. }
  16.  
  17. html,
  18. body {
  19. height: 100%;
  20. width: 100%;
  21. font-family: Apple Chancery, cursive;
  22. }
  23. .fs-7 {
  24. font-size: .8rem!important;
  25. }
  26. #list-data th{
  27. cursor:pointer;
  28. }
  29. .sort-asc, .sort-desc{
  30. position:relative;
  31. }
  32. .sort-asc:before{
  33. position:absolute;
  34. content:"";
  35. top: 5px;
  36. left: -18px;
  37. border-left: 5px solid transparent;
  38. border-right: 5px solid transparent;
  39. border-bottom: 9px solid #646464;
  40. }
  41. .sort-desc:before{
  42. position:absolute;
  43. content:"";
  44. top: 5px;
  45. left: -18px;
  46. border-left: 5px solid transparent;
  47. border-right: 5px solid transparent;
  48. border-top: 9px solid #646464;
  49. }
  50. </style>
  51. </head>
  52.  
  53. <body class="bg-light">
  54. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient" id="topNavBar">
  55. <div class="container">
  56. <a class="navbar-brand" href="https://sourcecodester.com">
  57. Sourcecodester
  58. </a>
  59. </div>
  60. </nav>
  61. <div class="container py-3" id="page-container">
  62. <small>How to sort Table Column Data using jQuery</small>
  63. <hr>
  64. <table class="table table-striped table-hover" id="list-data">
  65. <col width="10%">
  66. <col width="40%">
  67. <col width="20%">
  68. <col width="30%">
  69. <th class="py-1 px-2 text-center">#</th>
  70. <th class="py-1 px-2 text-center">Name</th>
  71. <th class="py-1 px-2 text-center">Number</th>
  72. <th class="py-1 px-2 text-center">Word</th>
  73. </thead>
  74. </table>
  75. </div>
  76.  
  77. </body>
  78.  
  79. </html>

Creating the JSON File

Next, the following script is the JSON Data which is the source of data of our table. It will be fetched using Ajax Request when the page or window is ready. Save the file as data.json.

  1. [{
  2. "name": "Aimee Hahn",
  3. "numberrange": 0,
  4. "text": "sit amet lorem semper auctor. Mauris vel turpis. Aliquam adipiscing"
  5. },
  6. {
  7. "name": "Otto Schultz",
  8. "numberrange": 3,
  9. "text": "et magnis dis parturient montes, nascetur ridiculus mus. Proin vel"
  10. },
  11. {
  12. "name": "Winifred Rush",
  13. "numberrange": 3,
  14. "text": "aliquet nec, imperdiet nec, leo. Morbi neque tellus, imperdiet non,"
  15. },
  16. {
  17. "name": "Brianna Gates",
  18. "numberrange": 5,
  19. "text": "Duis risus odio, auctor vitae, aliquet nec, imperdiet nec, leo."
  20. },
  21. {
  22. "name": "Stella Merritt",
  23. "numberrange": 5,
  24. "text": "cursus luctus, ipsum leo elementum sem, vitae aliquam eros turpis"
  25. },
  26. {
  27. "name": "Orson Rivas",
  28. "numberrange": "1",
  29. "text": "Morbi neque tellus, imperdiet non,"
  30. }, {
  31. "name": "Jessica Oliver",
  32. "numberrange": 9,
  33. "text": "Nulla facilisis. Suspendisse commodo tincidunt nibh. Phasellus nulla. Integer vulputate,"
  34. },
  35. {
  36. "name": "Fuller Mcdaniel",
  37. "numberrange": 2,
  38. "text": "at, iaculis quis, pede. Praesent eu dui. Cum sociis natoque"
  39. },
  40. {
  41. "name": "Magee Stark",
  42. "numberrange": 1,
  43. "text": "a feugiat tellus lorem eu metus. In lorem. Donec elementum,"
  44. },
  45. {
  46. "name": "Holly Small",
  47. "numberrange": 10,
  48. "text": "dui. Fusce aliquam, enim nec tempus scelerisque, lorem ipsum sodales"
  49. },
  50. {
  51. "name": "Karleigh Kelley",
  52. "numberrange": 9,
  53. "text": "nec orci. Donec nibh. Quisque nonummy ipsum non arcu. Vivamus"
  54. }, {
  55. "name": "Geoffrey Mays",
  56. "numberrange": 9,
  57. "text": "Nam tempor diam dictum sapien. Aenean massa. Integer vitae nibh."
  58. },
  59. {
  60. "name": "Hermione Brooks",
  61. "numberrange": 3,
  62. "text": "lectus. Nullam suscipit, est ac facilisis facilisis, magna tellus faucibus"
  63. },
  64. {
  65. "name": "Barry Johns",
  66. "numberrange": 3,
  67. "text": "leo elementum sem, vitae aliquam eros turpis non enim. Mauris"
  68. },
  69. {
  70. "name": "Hillary Aguilar",
  71. "numberrange": 4,
  72. "text": "lorem lorem, luctus ut, pellentesque eget, dictum placerat, augue. Sed"
  73. },
  74. {
  75. "name": "Quinlan Moss",
  76. "numberrange": 9,
  77. "text": "rutrum lorem ac risus. Morbi metus. Vivamus euismod urna. Nullam"
  78. }
  79. ]

Creating the Main Function

Lastly, the script below is the Custom JavaSript file for our application which contains the Jax Request Function for populating the Table rows and the sorting function. Save this file as script.js

  1. $(function() {
  2. $.ajax({
  3. url: 'data.json',
  4. dataType: 'json',
  5. error: err => {
  6. console.log(err)
  7. alert("An error occured while loading the table data. Please refresh the page");
  8. },
  9. success: function(resp) {
  10. if (resp.length > 0) {
  11. var i = 1;
  12. Object.keys(resp).map(k => {
  13. var data = resp[k]
  14. var tr = $('<tr>')
  15. tr.append('<td class="py-1 px-2 text-center">' + (i++) + '</td>')
  16. tr.append('<td class="py-1 px-2">' + (data.name) + '</td>')
  17. tr.append('<td class="py-1 px-2">' + (data.numberrange) + '</td>')
  18. tr.append('<td class="py-1 px-2">' + (data.text) + '</td>')
  19. $('#list-data tbody').append(tr)
  20. })
  21. }
  22. }
  23. })
  24. $('#list-data th').click(function() {
  25. var dir = $(this).attr('data-dir') || 'desc';
  26. dir = dir == 'desc' ? 'asc' : 'desc';
  27. $(this).attr('data-dir', dir)
  28. var dir_icon = '<span class="ms-4 fw-bold sort-' + dir + '"></span>'
  29. $('#list-data thead').find('.sort-asc').remove()
  30. $('#list-data thead').find('.sort-desc').remove()
  31. $(this).append(dir_icon)
  32. sort_element($(this).index(), dir)
  33. })
  34.  
  35. })
  36.  
  37. function sort_element(tbl_nth, dir) {
  38. tbl_nth = tbl_nth + 1
  39. var sorted = $($('#list-data tbody tr td:nth-child(' + tbl_nth + ')').toArray().sort(function(a, b) {
  40. var Aelement = a.innerText,
  41. Belement = b.innerText;
  42. if ($.isNumeric(Aelement) && $.isNumeric(Belement)) {
  43. if (dir == 'asc')
  44. return Aelement - Belement;
  45. else
  46. return Belement - Aelement;
  47. } else {
  48. if (dir == 'asc')
  49. return Aelement.localeCompare(Belement)
  50. else
  51. return Belement.localeCompare(Aelement)
  52. }
  53.  
  54. }))
  55. // console.log(sorted)
  56.  
  57. Object.keys(sorted).map(k => {
  58. $(sorted[k]).closest('tr').detach().appendTo('#list-data tbody')
  59. })
  60. }

There you go! You can now test the simple Web Application which has an HTML Table with Column Sorting Functionality on your end. Browse the index.html in your browser and see if it is working according to plan. If you have encountered an error, kindly review your source code or download the working source code I created for this tutorial. The download button is located below this article.

DEMO VIDEO

That's the end of this tutorial. I hope this tutorial will help you and your future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment