Results 1 to 5 of 5

Thread: select an option in a dropdown menu

  1. #1
    Join Date
    Nov 2005
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default select an option in a dropdown menu

    Hello,
    Is there a way javascript can select an option in a dropdown by giving its value?

    example:

    in this dropdown:

    <select name="choices" size="1">
    <option value="choice1">Choice 1</option>
    <option value="choice2">Choice 2</option>
    <option value="choice3">Choice 3</option>
    </select>

    I would like javascript to do this:

    make an option in the dropdown "choices" selected where the value is = choice2

    Thanks

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Not directly by value, no. Try this:
    Code:
    function selectValueFromSelect(/*HTMLSelectElement*/ sel, /*String*/ val) {
      for(var i=0;sel.options[i].value != val;i++) void(0);
      sel.selectedIndex = i;
    }
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. #3
    Join Date
    Nov 2005
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    i am a javascript noob, so could you please show me an example?

  4. #4
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Of how to use the function? Of course...
    Code:
    selectValueFromSelect(document.getElementsByName("choice")[0], "choice2");
    Better than document.getElementsByName() would be to use the forms and elements collections.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  5. #5
    Join Date
    Nov 2005
    Posts
    29
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Thank you a lot, that worked great

Bookmarks

Posting Permissions

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