Search code examples
htmlselectinternet-explorer-11html-selectdefault

Set the selected option as the first option in the selectbox


Open this link in IE to exactly understand the behavior that I will be describing and seek a hack for.

I have the following select list:

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select> 

When I render this in IE, drop-down behavior of this changes compared to other browsers due to which some of the options are pushed above the selectbox while the others are pushed below (based on the selected option)

Since this is the default behavior of IE, what I am looking for is that the options should get re-ordered i.e. the option that a user selects should be made the first option. Check the image below:

enter image description here

Does anyone have a work-around for this ?

Also if anyone knows a hack to alter this default IE behavior, it would be great to know and learn that

Is this the right way ?

<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
var choose = $("#choose").bind('change',function(){alert("hello");
choose.find('option:selected').prependTo(choose);
});
});
</script>
<head>
<body>

<select id="choose">
<option value="choose">choose</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

</body>
</html>

Solution

  • Here is a method that works in Jquery:

    HTML

    <select id = "choose">
        <option value="null" name="volvo">Volvo</option>
        <option value="1" name="saab">Saab</option>
        <option value="2" name="mercedes">Mercedes</option>
        <option value="3" name="audi">Audi</option>
    </select>
    

    jQuery

    var choose = $("#choose").bind('change',function(){
        choose.find('option:selected').prependTo(choose);
    });
    

    (Source)

    FULL CODE

    <!DOCTYPE html>
    <html>
    
    <head>
      <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
      <script>
        $(document).ready(function() {
          var choose = $("#choose").bind('change', function() {
            alert("hello");
            choose.find('option:selected').prependTo(choose);
          });
        });
      </script>
    
      <head>
    
        <body>
    
          <select id="choose">
            <option value="choose">choose</option>
            <option value="saab">Saab</option>
            <option value="opel">Opel</option>
            <option value="audi">Audi</option>
          </select>
    
        </body>
    
    </html>