jquery - Javascript Not Sorting Prices Correctly -


i'm sorting list of prices code:

var $divs = $("div.machinebox"); var numericallyordereddivs = $divs.sort(function (a, b) {             return $(a).find("p.price").text() < $(b).find("p.price").text() ? 1 : -1; }); $("#machinewrapper").html(numericallyordereddivs);  

i want sort list of prices highest lowest, this:

$549.00   $387.00   $248.99   $242.91   $97.01   $32.04   

the problem it's sorting them this:

$97.01   $549.00   $387.00   $32.04   $248.99   $242.91   

any ideas how sort properly? thanks!

for quick fix recommend storing unformatted value in attribute on element. problem it's sorting characters, not numerically.

try instead:

var $divs = $("div.machinebox"); var numericallyordereddivs = $divs.sort(function (a, b) {             return parsefloat($(a).attr('data-sort')) < parsefloat($(b).attr('data-sort')) ? 1 : -1; }); $("#machinewrapper").html(numericallyordereddivs);  

in case, whenever have .price item, set data-sort value parent div (to optimize sort bit). can parse float on value compare strings.

example html:

<div class="machinebox" data-sort="1367.42" >   <a class="price">$1,367.42</a> </div> 

for better solution: highly recommend use mv* framework/library better handle union of logic , ui. it's better practice sort models render/update views. popular backbone.js, angular.js, ember.js. (backbone great starting out, easy implement , helps teach great practices.)


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -