Menu Close

How To Sort a Table Using Jquery

Sort table jquery

Here, we will see how to sort a table with an ascending and descending order by using jquery sorting method. It will sort every row of the html table with the values according to its data types. Follow the below example to create this.

Example

Create a html file on your computer and add the below codes to this file.

<!DOCTYPE html>
<html> 
<head>
    <title>How To Sort a Table Using Jquery</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    
</head>
<body>
    <table>
    <thead>
      <tr>
        <th data-type="string">Name</th>
        <th data-type="string">Team</th>
        <th data-type="number">Score</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Col Fays</td>
        <td>Green</td>
        <td class="score">76</td>
      </tr>
      <tr>
        <td>Greg Arias</td>
        <td>Red</td>
        <td class="score">94</td>
      </tr>
      <tr>
        <td>Art Decco</td>
        <td>Green</td>
        <td class="score">75</td>
      </tr>
      <tr>
        <td>Ben Dover</td>
        <td>Blue</td>
        <td class="score">63</td>
      </tr>
      <tr>
        <td>Dee Zynah</td>
        <td>Blue</td>
        <td class="score">92</td>
      </tr>
      <tr>
        <td>Manny Jah</td>
        <td>Red</td>
        <td class="score">55</td>
      </tr>
    </tbody>
  </table>
</body>  
    <script>         
        $(function() {
            const ths = $("th");
            let sortOrder = 1;
        ths.on("click", function() {
            const rows = sortRows(this);
            rebuildTbody(rows);
            updateClassName(this);
            sortOrder *= -1;
            })
        function sortRows(th) {
            const rows = $.makeArray($('tbody > tr'));
            const col = th.cellIndex;
            const type = th.dataset.type;
            rows.sort(function(a, b) {
            return compare(a, b, col, type) * sortOrder;      
            });
        return rows;
        }
        function compare(a, b, col, type) {
            let _a = a.children[col].textContent;
            let _b = b.children[col].textContent;
            if (type === "number") {
                _a *= 1;
                _b *= 1;
            } else if (type === "string") {
                _a = _a.toLowerCase();
                _b = _b.toLowerCase();
            }
            if (_a < _b) {
                return -1;
            }
            if (_a > _b) {
                return 1;
            }
                return 0;
        }
        function rebuildTbody(rows) {
            const tbody = $("tbody");
            while (tbody.firstChild) {
            tbody.remove(tbody.firstChild);
            }
            let j;
            for (j=0; j<rows.length; j++) {
            tbody.append(rows[j]);
            }
        }
        function updateClassName(th) {
            let k;
            for (k=0; k<ths.length; k++) {
            ths[k].className = "";
            }
            th.className = sortOrder === 1 ? "asc" : "desc";   
        }  
    }); 
    </script>
</html>
 

Create an external stylesheet, add the below css to this file and link in to your html file to view the better design.

body {
    margin:50px;
    font-family: Arial, sans-serif;
    padding: 50px;
    background: #fafafa;
}

table {
    width: 540px;
    margin: 20px auto;
    border-collapse: collapse;
    border:1px solid #333;
}

tbody tr td{
    border-right-color:#333;
    border-right-width:1px solid;
}

thead tr th{
    border-right-color:#333;
    border-right-width:1px solid;
}

th, td {
    width: 180px;
    box-sizing: border-box;
    border: 1px solid #e9eae8;
    padding: 8px 20px;
}

tbody tr:nth-child(odd) {
    background-color: #f8f8f8;
}

.score {
    text-align: right;
}

th {
    cursor: pointer;
}

th::after {
    content: "\f0dc";
    font-family: FontAwesome;
    font-size: 12px;
    color: #cdc;
    float: right;
    padding-top: 4px;
}

th.asc::after {
    content: "\f0de";
    font-family: FontAwesome;
    color: #333;
}

th.desc::after {
    content: "\f0dd";
    font-family: FontAwesome;
    color: #333;
} 
Posted in HTML, jQuery

You can also read...