How to select a value in a select dropdown with JavaScript?

378,914

Solution 1

Use the selectedIndex property:

document.getElementById("Mobility").selectedIndex = 12; //Option 10

Alternate method:

Loop through each value:

//Get select object
var objSelect = document.getElementById("Mobility");

//Set selected
setSelectedValue(objSelect, "10");

function setSelectedValue(selectObj, valueToSet) {
    for (var i = 0; i < selectObj.options.length; i++) {
        if (selectObj.options[i].text== valueToSet) {
            selectObj.options[i].selected = true;
            return;
        }
    }
}

Solution 2

easiest way is to just use this

document.getElementById("mySelect").value = "banana";

myselect is name of your dropdown banana is just one of items in your dropdown list

Solution 3

function setSelectedIndex(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        if ( s.options[i].value == v ) {
            s.options[i].selected = true;
            return;
        }
    }
}

Where s is the dropdown and v is the value

Solution 4

The simplest possible solution if you know the value

document.querySelector('option[value=" + value +"]').selected = true

Solution 5

I realize that this is an old question, but I'll post the solution for my use case, in case others run into the same situation I did when implementing James Hill's answer (above).

I found this question while trying to solve the same issue. James' answer got me 90% there. However, for my use case, selecting the item from the dropdown also triggered an action on the page from dropdown's onchange event. James' code as written did not trigger this event (at least in Firefox, which I was testing in). As a result, I made the following minor change:

function setSelectedValue(object, value) {
    for (var i = 0; i < object.options.length; i++) {
        if (object.options[i].text === value) {
            object.options[i].selected = true;
            object.onchange();
            return;
        }
    }

    // Throw exception if option `value` not found.
    var tag = object.nodeName;
    var str = "Option '" + value + "' not found";

    if (object.id != '') {
        str = str + " in //" + object.nodeName.toLowerCase()
              + "[@id='" + object.id + "']."
    }

    else if (object.name != '') {
        str = str + " in //" + object.nodeName.toLowerCase()
              + "[@name='" + object.name + "']."
    }

    else {
        str += "."
    }

    throw str;
}

Note the object.onchange() call, which I added to the original solution. This calls the handler to make certain that the action on the page occurs.

Edit

Added code to throw an exception if option value is not found; this is needed for my use case.

Share:
378,914

Related videos on Youtube

karthick
Author by

karthick

A few selected Answers How to convert an image to pixels, edit it, and draw the edited image in Javascript When do browsers download sourcemaps? How to use a regex to match if any pattern appears once out of many times in a given sequence Javascript user-agent (ajax) different to sent user-agent when requesting website How to create a PDF with Puppeteer in a node environment without writing it to disk Working "Copy to Clipboard" function doesn't work when called in bootstrap modal Why is this not workin on SCSS Clicking New Chat Icon in Whatsapp Web using Javascript Hacker Rank Annagrams Individually Compiling SCSS Files in Gulp Sass each function is compiling with dollar sign in front of it

Updated on July 05, 2022

Comments

  • karthick
    karthick almost 2 years

    i have a drop down like this

    <select style="width: 280px" id="Mobility" name="Mobility">
      <option selected="">Please Select</option>
      <option>K</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
      <option>7</option>
      <option>8</option>
      <option>9</option>
      <option>10</option>
      <option>11</option>
      <option>12</option>
    </select>
    

    I use this line to select a value it works in Mozilla not in IE? Why its not working?

    var element = document.getElementById("Mobility");
    element.value = "10";
    
    • Sam
      Sam over 12 years
      possible duplicate of select <select> item by value
    • Admin
      Admin almost 8 years
      Refer this article: javascriptstutorial.com/blog/…
    • Ripon Al Wasim
      Ripon Al Wasim over 6 years
      How to do if there is no element ID? I have the name of element.
    • karthick
      karthick over 6 years
      @RiponAlWasim you can use document.getElementsByName var element = document.getElementsByName("Mobility")[0];
  • Dylan Valade
    Dylan Valade over 12 years
    I definitely prefer James Hill's approach to this one but it still might be useful for someone
  • karthick
    karthick over 12 years
    is there anyway without using selectedIndex?
  • James Hill
    James Hill over 12 years
    @GregM, based on the HTML in the OP this won't work. s.options[i].value should be s.options[i].text.
  • James Hill
    James Hill over 12 years
    @GregM, The OP doesn't specify a value for the options, only text.
  • GregM
    GregM over 12 years
    Ok yeah your right :(, will let my answer there in case he puts some value ;)
  • Mehdi Karamosly
    Mehdi Karamosly over 10 years
    it works in case he specify value in the options like <option value="K">K</option>
  • finnTheHumin
    finnTheHumin over 10 years
    and please take note of the date. This comment is written on 2011. I just tried .value on IE8 and it works fine. just an FYI. :)
  • Ripon Al Wasim
    Ripon Al Wasim over 6 years
    How to do if I have the name of element instead of ID?
  • Agnel Vishal
    Agnel Vishal over 4 years
    Where did 'Seven' come from?
  • m4heshd
    m4heshd about 4 years
    Works perfectly.
  • OzzyCzech
    OzzyCzech about 3 years
    this should be best answer