javascript - Sorting a HTML structure -


im trying sort div structure based on paramter using small javscript found.

it seems not perform expected. understand sorting function not parsing values perfectly...

this sorting logic use...

<script type="text/javascript">     // sorting logic      $(function() {         $("a[href*=#]").click(function(e) {             e.preventdefault();             var licontents = [];             $('#productprice span[id*="absprice"]').each(function() {                 licontents.push($(this).html());             });             licontents.sort(numorddesc);             $('#productprice span[id*="absprice"]').each(function() {                 $(this).html(licontents.pop());             });         });     });        function numorddesc(a, b) {         return (parseint(b) - parseint(a)); }     // end 

of sorting logic since cannot post html going add link actual website can see action. can point out going wrong?

http://www.absbiz.co.uk/products/tabid/85/rvdsfcatid/modems-437/default.aspx

edit: currently think sort working, still cannot move individual products. prices sorted , changed....

i took @ @ live site , injected sorting function used in question. noticed few things. firstly, strings passing compare function this:

"£38.89 ex. vat" "£19.93 ex. vat" "£44.44 ex. vat" ... 

so parseint("£38.89 ex. vat") return nan. no compare. can adjust remove non-decimal information, , parse float instead, so:

parsefloat("£38.89 ex. vat".replace(/[^0-9\.]/g, "")); // --> 38.89 

however, sort above price strings, don't have association information on products sort them in dom (yet). need adjust put array.


the strategy find top item containers using $('.productlistproductitem') , push html array. sort array such prices found $('#productprice span[id*="absprice"]') , stripped of non-decimal information. each top item container repopulated html sorted array.

essential code:

var licontents = [];  // push in product containers' innerhtml $('.productlistproductitem').each(function () {    licontents.push($(this).html()); });   // use our new sorting routine licontents.sort(numorddesc);   // replace html of each top item container $('.productlistproductitem').each(function () {    $(this).html(licontents.pop()); });  // pass in jquery elements, not strings function numorddesc($a, $b) {    // price further down in dom    var = $('#productprice span[id*="absprice"]', $a).text();    var b = $('#productprice span[id*="absprice"]', $b).text();    return parsefloat(b.replace(/[^0-9\.]/g, "")) - parsefloat(a.replace(/[^0-9\.]/g, "")); } 

to verify works, navigate live site , open devtool > console. copy above script , paste console. hit return, , note products sorted in ascending order. enjoy.


before:

before

after:

after


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -