Sort Dropdown
Sort the Select dropdown
by Abhijeet Deshmukh
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<button type=button>Sort Options</button>
<select class='whatever'>
<option value='22'>Hello</option>
<option value='101'>Banana</option>
<option value='1'>Sugar Cane</option>
<option value='-2'>Palm Oil</option>
</select>
JavaScript
$('button').click(function() {
var options = $('select.whatever option');
var arr = options.map(function(index, elm) {
return {
text: $(elm).text(),
value: elm.value
};
}).get();
arr.sort(function(elm1, elm2) {
var result = 0;
if (elm1.text > elm2.text) {
result = 1;
} else if (elm1.text < elm2.text) {
result = -1;
}
return result;
//return elm1.text > elm2.text ? 1 : elm1.text < elm2.text ? -1 : 0;
});
options.each(function(index, elm) {
elm.value = arr[index].value;
$(elm).text(arr[index].text);
});
});