Search code examples
htmljquerydrop-down-menudropdown

Move selected option at top of drop down menu


Script

var tkopt = {"c":"C","cs":"C#","d":"D","ef": "Eb","e":"E","f":"F","fs":"F#","g":"G","af":"Ab","a":"A","bf":"Bb","b":"B"};  
 $(document).ready(function(){     
   var sel = $("#tlist");
   $.each(tkopt, function(index, value){
     $("<option/>",{ value : index, text : value}).appendTo(sel);
   });
   $(function() {
     $("#tlist").val('e');
   });
 }); 
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

</head>
<body>
<select id="tlist">
</select>
</body>
</html>

The options provided here is just musical root keys. Here I made option E as selected option. Now I need the options above E to be appended at end of the option lists. i.e. option C should follow B at down, which is followed by C#, so on upto option Eb which follows option D. Please help me with jquery code.


Solution

  • You can use

    $(this).find("option:selected").index()
    

    to get the currently selected option's index, then move all the ones before it to the end in one step:

    sel.find("option").filter((i, e) => $(e).index() < idx).appendTo(sel);
    

    Updated snippet:

    var tkopt = {"c":"C","cs":"C#","d":"D","ef": "Eb","e":"E","f":"F","fs":"F#","g":"G","af":"Ab","a":"A","bf":"Bb","b":"B"};
    
    $(document).ready(function() {
      var sel = $("#tlist");
      $.each(tkopt, function(index, value) {
        $("<option/>", {
          value: index,
          text: value
        }).appendTo(sel);
      });
    
      sel.change(function() {
        var idx = $(this).find("option:selected").index();
        sel.find("option").filter((i, e) => $(e).index() < idx).appendTo(sel);
      });
    
      $("#tlist").val('e').change();
    });
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <select id="tlist"> </select>