javascriptjquerysortingoptgroup

Sort Select Option In Optgroup JQUERY


I have a select like below, and i want to sort this select in alphabetical order. (with Jquery)

<select>
  <optgroup label="Potatoes" >
    <option value="1" > Value 1 </option>
    <option value="3" > Value 3 </option>
    <option value="2" > Value 2 </option>
   </optgroup>

   <optgroup label="Banana" >
    <option value="1" > C </option>
    <option value="3" > A </option>
    <option value="2" > S </option>
   </optgroup>
 </select>

I only want to sort the options inside the optgroup. I don't want to sort the optgroup.

In order to have :

<select>
  <optgroup label="Potatoes" >
    <option value="1" > Value 1 </option>
    <option value="2" > Value 2 </option>
    <option value="3" > Value 3 </option>
   </optgroup>

   <optgroup label="Banana" >
      <option value="3" > A </option>
      <option value="1" > C </option>
      <option value="2" > S </option>
   </optgroup>
 </select>

I only found a way to sort the select with the optgroups...


Solution

  • This might be what you are looking for: https://jsfiddle.net/dt3b6fmc/

    $(function() {
      $('optgroup').each(function() {
        var optgroup = this;
        $( 'option', this ).sort(function(a,b) {
         return $(a).text() > $(b).text();
            }).appendTo(optgroup);
      });
    });
    

    Does that satisfy your needs?