I have a JSON array loaded into a JQuery mobile list. I have 4 radio buttons to sort the list. All working.
Plus, I have a filter bar to search through the sorted results. So let’s say I sorted my list by price ascending, I can search the list with the filter bar. But if I click price descending, the list automaticaly refresh to default.
So what i’m trying to do is sort by name ascending, filter through the results with the search bar, and if I click another sort button, the list doesnt refresh.
I hope you can understand me, I explained this as clearly as I can. Heres my code :
var productList = {"products": [ {"brand": "brand1", "description": "Product 1", "price": "03.25 "}, {"brand": "brand2", "description": "Product 4", "price": "01.10 "}, {"brand": "brand3", "description": "Product 3", "price": "04.21 "}, {"brand": "brand4", "description": "Product 2", "price": "15.24 "}, {"brand": "brand5", "description": "Product 5", "price": "01.52 "}, {"brand": "brand6", "description": "Product 6", "price": "12.01 "}, {"brand": "brand7", "description": "Product 7", "price": "05.24 "}] };
$(document).ready(function() {
console.debug('ready'); $('#sort > input[type = "radio"]').next('label').click( function(event, el) { console.debug($(event.currentTarget).prev('input').attr('id')); sortID = $(event.currentTarget).prev('input').attr('id'); refresh(sortID); });});
function refresh(sortID) {
var list = $("#productList").listview();
$(list).empty();var prods = productList.products.sort(function(a, b) {
switch (sortID) {
case 'sort-a-z':
return a.description > b.description;case 'sort-z-a':
return a.description < b.description;case 'sort-price-up':
return parseInt(a.price) > parseInt(b.price);case 'sort-price-down':
return parseInt(a.price) < parseInt(b.price);default:
return a.description > b.description;}
});
$.each(prods, function() {
list.append("<li>" + this.description + " : " + this.price + "</li>");
});$(list).listview("refresh");
}
I am not sure what is exactly the problem but I do know you shouldn’t be using parseInt to compare the prices like that.
parseInt can take a radix parameter, so that parseInt(“08”, 10) produces 8.
for the best result use parseFloat and then multiply the result by 100 to produce a whole number – then when you’ll compare the prices you’ll avoid all quircks of the javascript floating point system.
beyond that the code you shared looks okay to me.