user6104636 user6104636 - 6 months ago 39
HTML Question

how to make newly selected html option the first choice?

This is a simple problem that I cannot solve. Needless to say, I'm new to javascript.

I have sorted a dropdown list in alphabetical order, except for the first option as it has the selected value. Now when a user chooses a different value, I want that choice to be the first option and the rest in alphabetical order.

Do I need to have a sort in javascript to do this, or is there a function to 'append to the top of the list'?

sort in html is twig for sorting. I'm not using a js function...

html

<div class = "dropdowns">
<select id = "dropdown">
<option selected> name </option>
{% for key, value in Informations|sort %}
<option value="{{ key }}"> {{ value }} </option>
{% endfor %}
</select>
</div>


js

// Set textfield input to selected dropdown option
var myTextBox = document.getElementById('Infos');
var myDropdown = document.getElementById('dropdown');

document.addEventListener("DOMContentLoaded", function(event) {
$("select").change().append($("#dropdown"));
// $("#dropdown").val($("#dropdown option:select").val());
// myDropdown.value = myTextBox.value
})

myDropdown.onchange = function () {
myTextBox.value = this.value;
}
myDropdown.value = myTextBox.value

Answer

I hope this will definitely solve your need..

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    $(document).on('change','#dropdown',function(){

      $(this).html($('option',this).sort(function(a,b)
                                         {
        if(a.text == b.text)
        {
          return 0;
        }
        if(a.text > b.text)
        {
          return 1;
        }
        else
        {
          return -1;
        }
      }));

      var hold = $('option:selected',this).detach();
      $(this).prepend(hold);
    });
  });
</script>
<body>

  <div class = "dropdowns">
    <select id = "dropdown">
      <option selected> x</option>
      <option>a</option> 
      <option>r</option>   
      <option>d</option>  
      <option>c</option>  
    </select>
  </div>
</body>