How to set the selected index of a dropdown using javascript

16,798

Solution 1

How can I set the selected value of a dropdown using javascript?

So, you want to change the value of the option that is currently selected. Is that correct?

function setValueOfSelected(select, valueToSetTo){
    select.options[select.selectedIndex].value = valueToSetTo;
}

And call it like this:

setValueOfSelected(document.getElementById('strPlan'), 'selected');

Demo


In case you meant that you want to select an option based on its value, use this:

Declare this function:

function setOptionByValue(select, value){
    var options = select.options;
    for(var i = 0, len = options.length; i < len; i++){
        if(options[i].value === value){
            select.selectedIndex = i;
            return true; //Return so it breaks the loop and also lets you know if the function found an option by that value
        }
    }
    return false; //Just to let you know it didn't find any option with that value.
}

Now call that to set the option by value, like this, with the first parameter being the select element and the second being the value:

setOptionByValue(document.getElementById('strPlan'), '1');

Demo

Solution 2

Something like this could work, I believe:

function setDropDownList(elementRef, valueToSetTo)
{
    var isFound = false;

    for (var i = 0; i < elementRef.options.length; i++) {
        if (elementRef.options[i].value == valueToSetTo) {
            elementRef.options[i].selected = true;
            isFound = true;
        }
    }

    if ( isFound == false )
        elementRef.options[0].selected = true;
}

Found it here. Just Google for something like 'set selected value dropdown javascript' and you'll get many possible solutions.

Share:
16,798
jain ruchi
Author by

jain ruchi

Updated on June 05, 2022

Comments

  • jain ruchi
    jain ruchi almost 2 years

    How can I set the selected value of a dropdown using javascript?

    This is my HTML:

    <select id="strPlan" name="strPlan" class="formInput">
        <option value="0">Select a Plan</option>
    </select>
    

    I am using javascript to add values. Can anyone tell me how to call a function to select a value?