88

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";
isherwood
  • 58,414
  • 16
  • 114
  • 157
karthick
  • 11,998
  • 6
  • 56
  • 88

11 Answers11

131

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;
        }
    }
}
djvg
  • 11,722
  • 5
  • 72
  • 103
James Hill
  • 60,353
  • 20
  • 145
  • 161
36

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

Amin
  • 471
  • 4
  • 5
15
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

GregM
  • 2,634
  • 3
  • 22
  • 37
12

The simplest possible solution if you know the value

document.querySelector('option[value=" + value +"]').selected = true
Gabor
  • 121
  • 1
  • 2
7

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.

Community
  • 1
  • 1
Deacon
  • 3,615
  • 2
  • 31
  • 52
6

Using Javascript:

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

Using Jquery:

$('select').prop('selectedIndex', 3); // This will select the 4th option from the dropdown list
Makyen
  • 31,849
  • 12
  • 86
  • 121
6

Using some ES6:

Get the options first, filter the value based on the option and set the selected attribute to true.

window.onload = () => {

  [...document.querySelector(`#Mobility`).options]
    .filter(x => x.value === "12")[0]
    .setAttribute('selected', true);

};
<select style="width: 280px" id="Mobility" name="Mobility">
  <option selected disabled>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>
OzzyCzech
  • 9,713
  • 3
  • 50
  • 34
Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53
  • 1
    Note that in Typescript it actually needs to be `.setAttribute('selected', '');`, as the boolean type is not allowed here. This results correctly in ` – luckydonald Jul 14 '22 at 07:25
4

This may do it

document.forms['someform'].elements['someelement'].value

Community
  • 1
  • 1
Dylan Valade
  • 5,565
  • 6
  • 42
  • 56
1

Instead of doing

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;
        }
    }
}

I solved this problem by doing this

function setSelectedValue(dropDownList, valueToSet) {
    var option = dropDownList.firstChild;
    for (var i = 0; i < dropDownList.length; i++) {
        if (option.text.trim().toLowerCase() == valueToSet.trim().toLowerCase()) {
            option.selected = true;
            return;
        }
        option = option.nextElementSibling;
    }
}

If you work with strings, you should use the .trim() method, sometimes blank spaces can cause trouble and they are hard to detect in javascript debugging sessions.

dropDownList.firstChild will actually be your first option tag. Then, by doing option.nextElementSibling you can go to the next option tag, so the next choice in your dropdownlist element. If you want to get the number of option tags you can use dropDownList.length which I used in the for loop.

Hope this helps someone.

1

Yes. As mentioned in the posts, value property is nonstandard and does not work with IE. You will need to use the selectedIndex property to achieve this. You can refer to the w3schools DOM reference to see the properties of HTML elements. The following link will give you the list of properties you can work with on the select element.

http://www.w3schools.com/jsref/dom_obj_select.asp

Update

This was not supported during 2011 on IE. As commented by finnTheHuman, it is supported at present.

James Jithin
  • 10,183
  • 5
  • 36
  • 51
  • 1
    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. :) – finnTheHumin Oct 25 '13 at 04:21
0

I made two significant improvements to the excellent alternative method, which was much better suited to my requirements, that was included in the accepted answer by @Janes Hill.

  1. As written, the code in his answer matches against the display text of the combo box. I needed to match against the string specified in the value attribute of the option tag.

  2. To allow for the possibility that the input value is missing from the list, I wanted to return the selectedIndex so that it can be tested, returning an invalid index when that happens.

  3. As a matter of practice, I usually make all such evaluations case insensitive.

My improved function follows.

    function SetSelectedValue ( selectObj, valueToSet )
    {
        const value2SetLC = valueToSet.toLowerCase();

        for ( var i = 0; i < selectObj.options.length; i++ )
        {
            if ( selectObj.options [ i ].value.toLowerCase ( ) === value2SetLC )
            {
                selectObj.options [ i ].selected = true;
                return i;
            }   // if ( selectObj.options [ i ].value.toLowerCase ( ) === value2SetLC )
        }   // for ( var i = 0; i < selectObj.options.length; i++ )

        return -1;  // Value not found
    }   // function SetSelectedValue
David A. Gray
  • 1,039
  • 12
  • 19