Items order by goods price
I am trying to order various products from the site, but I cannot get it right.
Basically, I need to get the price of each one and order them from most expensive to least.
I tried the following code, but it all disappears and doesn't order them correctly:
var divList = $(".block-level.h2");
divList.sort(function(a, b){
return $(a).data(".block-level.h2")-$(b).data(".block-level.h2")
});
$(".grid").html(divList);
I don't have access to change the HTML, so this needs to be done with the code I have now, only things can be added via jQuery.
Can someone give me a hint or help me?
Thank.
source to share
For your query to sort the items of the product grid, there is code jQuery
that you can use.
var values = [];
$('.block-level.h2').each(function() {
var temp = Array();
temp['value'] = parseInt($(this).html().replace('$',''));
temp['element'] = $(this).closest('.grid-item');
values.push(temp);
});
values.sort(function(a,b) { return b.value - a.value; });
var sortedHtml = '';
$.each(values, function(index, obj) {
if((index+1)%3==1) {
sortedHtml+=('<div class="grid product-cards__row"><div class="grid-item one-third palm-one-whole product-cards__item">'+$(obj.element).html()+'</div>');
} else if((index+1)%3==0) {
sortedHtml+=('<div class="grid-item one-third palm-one-whole product-cards__item">'+$(obj.element).html()+'</div></div>');
} else {
sortedHtml+=('<div class="grid-item one-third palm-one-whole product-cards__item">'+$(obj.element).html()+'</div>');
}
});
$('.product-cards').html(sortedHtml);
Hope this helps!
source to share
This can be done by the following code -
var values = Array();
$('.block-level.h2').each(function() {
values.push(parseInt($(this).html().replace('$','')));
});
values.sort(function(a, b){return b-a});
In your code above - the main problem is $(a).data(".block-level.h2")
as it tries to find a named attribute on an data-.block-level.h2
element a
that doesn't exist. This is why the result is empty.
source to share