I have two drop downs in a form and i want to sort the values by alphabetic order.so i tried to implement by jquery. Actually it is working in ascending order but all drop down values are appearing in each drop downs which mean duplication occurring( first drop down values are appearing in second drop down and vice versa).
My code is
$(function() {
var select = $('select');
select.html(select.find('option').sort(function(x, y) {
return $(x).text() > $(y).text() ? 1 : -1;
}));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<select>
<option selected>Choose a number</option>
<option value="3">Three</option>
<option value="1">One</option>
<option value="0">Zero</option>
<option value="2">Two</option>
<option value="8">Eight</option>
</select>
<select>
<option selected>Choose a number</option>
<option value="3">cxbcbcb</option>
<option value="1">Obcbcbcne</option>
<option value="0">Zbcbero</option>
<option value="2">detygey</option>
<option value="8">eyeyeyy</option>
</select>
</div>
Here is a simple solution:-
$(function() {
// Loop for each select element on the page.
$("select").each(function() {
// Keep track of the selected option.
var selectedValue = $(this).val();
// Sort all the options by text. I could easily sort these by val.
$(this).html($("option", $(this)).sort(function(a, b) {
if(a.text == "Choose a number") return 1;
if(b.text == "Choose a number") return 1;
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));
// Select one option.
$(this).val(selectedValue);
});
});