GeoMaps GeoMaps - 5 months ago 14
HTML Question

How to sort items in a dropdown list ignoring accents using Jquery?

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>




Answer

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/