2

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?

Peter
  • 13,733
  • 11
  • 75
  • 122
jain ruchi
  • 245
  • 3
  • 5
  • 11

2 Answers2

8

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

Some Guy
  • 15,854
  • 10
  • 58
  • 67
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.

Peter
  • 13,733
  • 11
  • 75
  • 122