I'm having an issue trying to sort the list-items within an unordered-list when the values within the list-items are numbers. Sorting alphanumerically does not seem to be the answer and I am unsure of what to change in order to ensure the list is displayed in the correct order.
The problem occurs when the outcome like the following, obviously 10 does not come before 2:
- 1 Meter
- 10 Meter
- 2 Meter
Below is my code, any help would be greatly appreciated.
$(".filtersDropDown").each(function(){
$(this).html($(this).children('li').sort(function(a, b){
return ($(b).data('position')) < ($(a).data('position')) ? 1 : -1;
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="specificationFiltersDropDown1047" class="filtersDropDown">
<ul>
<li class="selected">
<a class="allFilterDropDownOptions">All</a>
</li>
<li>
<a class="filterItemUnselected" data-option-id="1209">1 Meter (3ft)</a>
</li>
<li>
<a class="filterItemUnselected" data-option-id="1288">10 Meter (33ft)</a>
</li>
<li>
<a class="filterItemUnselected" data-option-id="1291">2 Meter (7ft)</a>
</li>
</ul>
</div>
You can solve it by using the
parseInt()function. This will turn character numbers into numbers.Also, there were few errors on your code ass i couldnt find the data position and no
.find('ul')for your sort.Hope this is what you were looking for :)