JavaScript - How to Create a Sortable HTML Table with JavaScript

How to Sort HTML Table by Clicking on the Column Headers Using JavaScript


Javascript - Creating a Sortable HTML Table with JavaScript



In this Javascript tutorial, we will see how to implement dynamic sorting functionality for an HTML table
Users can click on column headers, each featuring a Font Awesome icon, to toggle between ascending and descending sorting for product data.



Project Source Code:



<!DOCTYPE html>
<html>
<head>
<title>Sort Table</title>
<!-- FontAwesome -->
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<style>
table{
border-collapse: collapse;
width: 100%;
max-width: 600px;
margin: 0 auto;
text-align: center;
font-family: Arial, sans-serif
}
thead th{
background-color: #3a3a3a;
color: #fff;
font-size: 18px;
text-transform: uppercase;
cursor: pointer;
}

tbody tr{border-bottom: 1px solid #ddd;}

tbody td:first-child{
font-weight: bold;
color: #222;
padding: 15px;
text-align: left;
}

tbody td:not(:first-child){
padding: 15px;
color: #555;
}

.fa-sort{ margin-left: 5px; }

tbody tr:hover{background-color: #f5f5f5;}

</style>



</head>
<body>
<table id="table">
<thead>
<tr>
<th id="product-column">Product <i class="fa fa-sort"></i></th>
<th id="stock-column">Stock <i class="fa fa-sort"></i></th>
<th id="price-column">Price <i class="fa fa-sort"></i></th>
</tr>
</thead>
<tbody>
<tr>
<td>Product 1</td>
<td>11</td>
<td>$52</td>
</tr>
<tr>
<td>Product 85</td>
<td>28</td>
<td>$21</td>
</tr>

<tr>
<td>Product 97</td>
<td>850</td>
<td>$145</td>
</tr>

<tr>
<td>Z Product 75</td>
<td>35</td>
<td>$28</td>
</tr>

<tr>
<td>X Product 102</td>
<td>3025</td>
<td>$31</td>
</tr>

<tr>
<td>W Product 45</td>
<td>66</td>
<td>$560</td>
</tr>

<tr>
<td>Product 729</td>
<td>953</td>
<td>$359</td>
</tr>
</tbody>

</table>


<script>

// Get the product table and its body, and all its rows
var table = document.getElementById("table");
var rows = table.querySelectorAll("tbody tr");

// Create an array of objects with the data from each row
var rowData = [];

for(var i = 0; i < rows.length; i++)
{
var cells = rows[i].getElementsByTagName("td");
var product = cells[0].innerHTML;
var stock = parseInt(cells[1].innerHTML);
var price = parseFloat(cells[2].innerHTML.replace("$",""));

rowData.push({product:product, stock:stock, price:price});

}

// Define the initial sort direction of each column
var sortDirection = {product:"asc", stock:"asc", price:"asc"};

// Sort the array by the price column initially
rowData.sort(function(a, b){
return a.price - b.price;

});

// Update the table with the sorted data
function updateTable(){

for(var i = 0; i < rowData.length; i++){
rows[i].getElementsByTagName("td")[0].innerHTML = rowData[i].product;
rows[i].getElementsByTagName("td")[1].innerHTML = rowData[i].stock;
rows[i].getElementsByTagName("td")[2].innerHTML = "$" + rowData[i].price;
}

}

// Call the function initially to populate the table
updateTable();

// Add event listeners to the sort icons
var productSortIcon = document.getElementById("product-column").getElementsByTagName("i")[0];
var stockSortIcon = document.getElementById("stock-column").getElementsByTagName("i")[0];
var priceSortIcon = document.getElementById("price-column").getElementsByTagName("i")[0];

// Sort the table when the product column header is clicked
productSortIcon.addEventListener("click", function(){

rowData.sort(function(a,b){

if(sortDirection.product === "asc"){

if(a.product < b.product) return -1;
if(a.product > b.product) return 1;

return 0;

}else
{
if(a.product < b.product) return 1;
if(a.product > b.product) return -1;

return 0;
}

});

sortDirection.product = (sortDirection.product === "asc") ? "desc":"asc";
updateTable();

});



stockSortIcon.addEventListener("click", function(){

rowData.sort(function(a,b){

if(sortDirection.stock === "asc")
return a.stock - b.stock;
else
return b.stock - a.stock;

});

sortDirection.stock = (sortDirection.stock === "asc") ? "desc":"asc";
updateTable();
});


priceSortIcon.addEventListener("click", function(){

rowData.sort(function(a,b){

if(sortDirection.price === "asc")
return a.price - b.price;
else
return b.price - a.price;

});

sortDirection.price = (sortDirection.price === "asc") ? "desc":"asc";
updateTable();
});



</script>


</body>
</html>




Code Explanation:

this JavaScript code, allows users to dynamically sort html table in an ascending or descending order.

Sorting Functionality: - When a sort icon is clicked for a specific column, it sorts the data accordingly.
- Toggles between ascending and descending order for each column.
- Calls the updateTable() function to refresh the table with the sorted data.



OUTPUT:




Share this

Related Posts

Previous
Next Post »