I am trying to sort products with price high to low and low to high. I have written code for this, but sorting is not working. After either sorting a blank page appears. i have checked in console, no error here. Placed console.log in function (sortlowTohigh) like console.log(sort low to high....), and it displays message in console the same way.
$(document).ready(function() {
// Function to sort products by price (low to high)
function sortByLowToHigh() {
var $productList = $('#product-list');
var $products = $productList.children('.product-box-3');
$products.sort(function(a, b) {
var priceA = parseFloat($(a).find('.price').text().replace('₹', '').replace(',', ''));
var priceB = parseFloat($(b).find('.price').text().replace('₹', '').replace(',', ''));
return priceA - priceB;
});
$productList.html($products);
}
// Function to sort products by price (high to low)
function sortByHighToLow() {
var $productList = $('#product-list');
var $products = $productList.children('.product-box-3');
$products.sort(function(a, b) {
var priceA = parseFloat($(a).find('.price').text().replace('₹', '').replace(',', ''));
var priceB = parseFloat($(b).find('.price').text().replace('₹', '').replace(',', ''));
return priceB - priceA;
});
$productList.html($products);
}
// Handle dropdown item click events
$('#low').click(function() {
sortByLowToHigh();
});
$('#high').click(function() {
sortByHighToLow();
});
// sortByLowToHigh(); price.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="top-filter-menu">
<div class="category-dropdown">
<h5 class="text-content">Sort By :</h5>
<div class="dropdown">
<button class="dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown">
<span>Most Popular</span> <i class="fa-solid fa-angle-down"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li>
<a class="dropdown-item" id="low" href="javascript:void(0)">Low - High Price</a>
</li>
<li>
<a class="dropdown-item" id="high" href="javascript:void(0)">High - Low Price</a>
</li>
</ul>
</div>
</div>
</div>
<div id="product-list" class="row g-sm-4 g-3 row-cols-xxl-4 row-cols-xl-3 row-cols-lg-2 row-cols-md-3 row-cols-2 product-list-section">
<div>
<div class="product-box-3 h-100 wow fadeInUp">
<a href="#">
<h5 class="name">Test 1</h5>
</a>
<h5 class="price"><span class="theme-color">₹7</span></h5>
</div>
<div class="product-box-3 h-100 wow fadeInUp">
<a href="#">
<h5 class="name">Test 2</h5>
</a>
<h5 class="price"><span class="theme-color">₹9</span></h5>
</div>
<div class="product-box-3 h-100 wow fadeInUp">
<a href="#">
<h5 class="name">Test 3</h5>
</a>
<h5 class="price"><span class="theme-color">₹1</span></h5>
</div>
<div class="product-box-3 h-100 wow fadeInUp">
<a href="#">
<h5 class="name">Test 4</h5>
</a>
<h5 class="price"><span class="theme-color">₹4</span></h5>
</div>
</div>
</div>