• We just launched and are currently in beta. Join us as we build and grow the community.

How to Sort Data of HTML Table Column using jQuery Tutorial

SloopNasty

Page Speed Optimizer
S Rep
0
0
0
Rep
0
S Vouches
0
0
0
Vouches
0
Posts
42
Likes
48
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
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. <head

    >
  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. <style

    >
  14. :root {
  15. --bs-success-rgb: 71, 222, 152 !important;
  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. <body

    class

    =

    "bg-light"

    >
  53. <nav class

    =

    "navbar navbar-expand-lg navbar-dark bg-primary bg-gradient"

    id

    =

    "topNavBar"

    >
  54. <div

    class

    =

    "container"

    >
  55. <a

    class

    =

    "navbar-brand"

    href

    =

    "https://sourcecodester.com"

    >
  56. Sourcecodester
  57. </

    a

    >
  58. </

    div

    >
  59. </

    nav>
  60. <div

    class

    =

    "container py-3"

    id

    =

    "page-container"

    >
  61. <small

    >

    How to sort Table Column Data using jQuery</

    small

    >
  62. <hr

    >
  63. <table

    class

    =

    "table table-striped table-hover"

    id

    =

    "list-data"

    >
  64. <colgroup

    >
  65. <col

    width

    =

    "10%"

    >
  66. <col

    width

    =

    "40%"

    >
  67. <col

    width

    =

    "20%"

    >
  68. <col

    width

    =

    "30%"

    >
  69. </

    colgroup

    >
  70. <thead

    >
  71. <th

    class

    =

    "py-1 px-2 text-center"

    >

    #</

    th

    >
  72. <th

    class

    =

    "py-1 px-2 text-center"

    >

    Name</

    th

    >
  73. <th

    class

    =

    "py-1 px-2 text-center"

    >

    Number</

    th

    >
  74. <th

    class

    =

    "py-1 px-2 text-center"

    >

    Word</

    th

    >
  75. </

    thead

    >
  76. <tbody

    ></

    tbody

    >
  77. </

    table

    >
  78. </

    div

    >

  79. </

    body

    >

  80. </

    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. function

    sort_element(

    tbl_nth,

    dir)

    {
  36. tbl_nth =

    tbl_nth +

    1
  37. var

    sorted =

    $(

    $(

    '#list-data tbody tr td:nth-child('

    +

    tbl_nth +

    ')'

    )

    .toArray

    (

    )

    .sort

    (

    function

    (

    a,

    b)

    {
  38. var

    Aelement =

    a.innerText

    ,
  39. Belement =

    b.innerText

    ;
  40. if

    (

    $.isNumeric

    (

    Aelement)

    &&

    $.isNumeric

    (

    Belement)

    )

    {
  41. if

    (

    dir ==

    'asc'

    )
  42. return

    Aelement -

    Belement;
  43. else
  44. return

    Belement -

    Aelement;
  45. }

    else

    {
  46. if

    (

    dir ==

    'asc'

    )
  47. return

    Aelement.localeCompare

    (

    Belement)
  48. else
  49. return

    Belement.localeCompare

    (

    Aelement)
  50. }

  51. }

    )

    )
  52. // console.log(sorted)

  53. Object

    .keys

    (

    sorted)

    .map

    (

    k =>

    {
  54. $(

    sorted[

    k]

    )

    .closest

    (

    'tr'

    )

    .detach

    (

    )

    .appendTo

    (

    '#list-data tbody'

    )
  55. }

    )
  56. }

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 :)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,292

324,736

324,744

Top