i issue sorting div elements price values. functionality of code works ok seems doesn't quite sort numbers correctly.
as can see jsfiddle when button pressed number 21.35 comes after numbers 102.35 , 200.
can shed light on this?
here html
<div class="wrap"> <button id="numbnt">numerical</button> <div id="container"> <div class="box"> <h2>10.35</h2> </div> <div class="box"> <h2>21.35</h2> </div> <div class="box"> <h2>21.35</h2> </div> <div class="box"> <h2>102.35</h2> </div> <div class="box"> <h2>10.35</h2> </div> <div class="box"> <h2>10.35</h2> </div> <div class="box"> <h2>10.95</h2> </div> <div class="box"> <h2>100.35</h2> </div> <div class="box"> <h2>100.05</h2> </div> <div class="box"> <h2>200</h2> </div> <div class="box"> <h2>5,510.25</h2> </div> </div> </div> and javascript
var $divs = $("div.box"); $('#numbnt').on('click', function () { var numericallyordereddivs = $divs.sort(function (a, b) { return $(a).find("h2").text() > $(b).find("h2").text(); }); $("#container").html(numericallyordereddivs); }); and here jsfiddle.
the reason you're getting these results sort not numeric, based upon canonical values of numbers.
the reason why 21.35 comes after number 102.35 because digit 1 in 102.35 smaller digit 2 in 21.35 , 0 in 200 smaller 1 in 21.35.
fix: parse numbers float , before sorting
var numericallyordereddivs = $divs.sort(function (a, b) { return parsefloat($(a).find("h2").text()) > parsefloat($(b).find("h2").text()); }); updated fiddle
Comments
Post a Comment