Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  41] [ 5]  / answers: 1 / hits: 17575  / 13 Years ago, tue, december 13, 2011, 12:00:00

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?


More From » asp-classic

 Answers
69

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


[#88585] Sunday, December 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bretd

Total Points: 6
Total Questions: 100
Total Answers: 97

Location: England
Member since Sun, May 21, 2023
1 Year ago
;