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 June 15, 2022

Comments

  • karthick
    karthick less than a minute

    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";
    
    • user7116
      user7116 over 10 years
      possible duplicate of select <select> item by value
    • Admin
      Admin about 6 years
      Refer this article: javascriptstutorial.com/blog/…
    • Ripon Al Wasim
      Ripon Al Wasim almost 5 years
      How to do if there is no element ID? I have the name of element.
    • karthick
      karthick almost 5 years
      @RiponAlWasim you can use document.getElementsByName var element = document.getElementsByName("Mobility")[0];
  • Dylan Valade
    Dylan Valade over 10 years
    I definitely prefer James Hill's approach to this one but it still might be useful for someone
  • karthick
    karthick over 10 years
    is there anyway without using selectedIndex?
  • James Hill
    James Hill over 10 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 10 years
    @GregM, The OP doesn't specify a value for the options, only text.
  • GregM
    GregM over 10 years
    Ok yeah your right :(, will let my answer there in case he puts some value ;)
  • Mehdi Karamosly
    Mehdi Karamosly over 8 years
    it works in case he specify value in the options like <option value="K">K</option>
  • finnTheHumin
    finnTheHumin over 8 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 almost 5 years
    How to do if I have the name of element instead of ID?
  • Agnel Vishal
    Agnel Vishal almost 3 years
    Where did 'Seven' come from?
  • m4heshd
    m4heshd over 2 years
    Works perfectly.
  • OzzyCzech
    OzzyCzech about 1 year
    this should be best answer