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?
Some Guy :
\n How can I set the selected value of a dropdown using javascript?\n\n\nSo, you want to change the value of the option that is currently selected. Is that correct?\n\nfunction setValueOfSelected(select, valueToSetTo){\n select.options[select.selectedIndex].value = valueToSetTo;\n}\n\n\nAnd call it like this:\n\nsetValueOfSelected(document.getElementById('strPlan'), 'selected');\n\n\nDemo\n\n\n\nIn case you meant that you want to select an option based on its value, use this:\n\nDeclare this function:\n\nfunction setOptionByValue(select, value){\n var options = select.options;\n for(var i = 0, len = options.length; i < len; i++){\n if(options[i].value === value){\n select.selectedIndex = i;\n return true; //Return so it breaks the loop and also lets you know if the function found an option by that value\n }\n }\n return false; //Just to let you know it didn't find any option with that value.\n}\n\n\nNow call that to set the option by value, like this, with the first parameter being the select element and the second being the value:\n\nsetOptionByValue(document.getElementById('strPlan'), '1');\n\n\nDemo",
2011-12-13T10:29:06