Set the selected option as the first option in the selectbox

ⅰ亾dé卋堺 提交于 2019-12-04 21:09:00
Arnav Borborah

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>
    <html>
<head>
    <script src="jquery-3.1.0.js"></script>
    <script>
        $(function () {
            var selectedItem = $("#selectItem").bind('change', function () {
                selectedItem.find('option:selected').prependTo(selectedItem);
            });
        });
    </script>
    <head>
        <body>

            <select id="selectItem">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
            <option value="4">four</option>
            </select>

        </body>
</html>

Thanks... :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!