I want to sort my dropdown list by a crescent order.
The following code (see snippet below) does what I want. However, it doesn't ignore the accents, and this is what I aim.
Could someone help me with that?
window.addEventListener("load", function () {
$("#MyID").html($("#MyID option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="MyID">
<option> Papél </option>
<option> Árvore </option>
<option> Carne </option>
<option> Banana </option>
<option> Água</option>
<option> Macaco</option>
<option> Maçã</option>
</select>
You can use localeCompare()
for this purpose.
window.addEventListener("load", function () {
$("#MyID").html($("#MyID option").sort(function (a, b) {
return (a.text).localeCompare(b.text);
//return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="MyID">
<option> Papél </option>
<option> Árvore </option>
<option> Carne </option>
<option> Banana </option>
<option> Água</option>
<option> Macaco</option>
<option> Maçã</option>
</select>
Refer this link for other methods: http://www.jstips.co/en/sorting-strings-with-accented-characters/