www.webdeveloper.com
Results 1 to 6 of 6

Thread: Dynamic Drop Down

  1. #1
    Join Date
    Apr 2012
    Location
    London
    Posts
    12

    Dynamic Drop Down

    Hi guys,

    Anyone knows how I could dynamically add selected index to a select option.

    Found this online but couldn't figure out how to add selected index to it.

    function addOption(selectbox, value, text)
    {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
    }

    addOption(frmadd.myselect,"1", "Weddings");

    Thanks for your help

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,671
    option has no selected index, the select element has this property.

  3. #3
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,270
    See this page Change Select element content in the fly and use the constructor new Option(text, value, defaultSelected, selected) !

  4. #4
    Join Date
    Apr 2012
    Location
    London
    Posts
    12
    Thanks 007Julien, will check that out

  5. #5
    Join Date
    Nov 2010
    Posts
    1,097
    if the option already exists and you just want it to be selected, it would be something like this (if "sel" were the id of your select and you wanted the 3rd option selected):

    Code:
    document.getElementById("sel").selectedIndex=2;
    you can also give your options id's and select them that way:

    Code:
    <body>
    <select>
    <option id="app">apples</option>
    <option id="or">oranges</option>
    <option id="pea">pears</option>
    </select>
    <input type="button" onclick="changeSel()" value ="change it!"/>
    <script type="text/javascript"> 
    function changeSel(){
    document.getElementById("pea").selected=true;
    }
    </script>
    </body>
    and all sorts of other stuff, depending on what it is that you actually want to do

  6. #6
    Join Date
    Apr 2012
    Location
    London
    Posts
    12
    Thanks guys, got it working perfectly but my problem is how to dynamically selected the a default value, I have tried using ternary operator inside the constructor but it didnt work.
    eg.
    document.frmadd.subcat.options[3]= new Option("Weddings", "8", false, (frmadd.subcat.value == '8')?true:false)

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles