I want to sort the html div in alphabetical order using data attribute value. I have the following code and would like to know, how can this be achieved
<div id="aphaOrder">
<div class="value" data-site="olark">olark</div>
<div class="value" data-site="snapengage">snapengage</div>
<div class="value" data-site="helponclick">helponclick</div>
<div class="value" data-site="hangouts">hangouts</div>
<div class="value" data-site="atlass">atlass</div>
<div class="value" data-site="hipchat">hipchat</div>
<div class="value" data-site="chat hip">chat hip</div>
<div class="value" data-site="force">force</div>
<div class="value" data-site="sugar sms">sugar sms</div>
<div class="value" data-site="capsule">capsule</div>
<div class="value" data-site="highrise">highrise</div>
<div class="value" data-site="nimble">nimble</div>
<div class="value" data-site="batch">batch</div>
<div class="value" data-site="book crm">book crm</div>
<div class="value" data-site="solve">solve</div>
<div class="value" data-site="insightly">insightly</div>
<div class="value" data-site="pipeliner">pipeliner</div>
<div class="value" data-site="shopify">shopify</div>
<div class="value" data-site="wordpress">wordpress</div>
<div class="value" data-site="Magento">Magento</div>
</div>
var alphabeticallyOrderedDivs = $('.value').sort(function(a,b){
return $(a).attr('data-site') > $(b).attr('data-site');
});
$("#aphaOrder").html(alphabeticallyOrderedDivs);
This is code is not giving the proper result. Please help me with this.
You can use String.prototype.localeCompare
JSFIDDLE here
var alphabeticallyOrderedDivs = $('.value').sort(function(a, b) {
return String.prototype.localeCompare.call($(a).data('site').toLowerCase(), $(b).data('site').toLowerCase());
});
var container = $("#aphaOrder");
container.detach().empty().append(alphabeticallyOrderedDivs);
$('body').append(container);
This should work:-
$("#aphaOrder .value").sort(function (a, b) {
if ( ($(a).attr("data-site").toLowerCase() > $(b).attr("data-site").toLowerCase()) ) {
return 1;
} else if ( ($(a).attr("data-site").toLowerCase() == $(b).attr("data-site").toLowerCase()) ){
return 0;
} else {
return -1;
}
}).each(function () {
var elem = $(this);
elem.remove();
$(elem).appendTo("#aphaOrder");
});
http://jsfiddle.net/0bs5mu6e/2/
You are try to get the attribute data-value
. There is no property like that. Check JSFIDDLE
Try this:
return $(a).data('site').toLowerCase() > $(b).data('site').toLowerCase();
or
return $(a).attr('data-site').toLowerCase() > $(b).attr('data-site').toLowerCase();
Output will be:
atlass
batch
book crm
capsule
chat hip
force
hangouts
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With