How can I set the selected value of a dropdown using javascript?
If you are looking to change the value of the currently selected option in a dropdown, you can achieve that with the following JavaScript code:
function setSelectedValue(selectElement, valueToSet){
selectElement.options[selectElement.selectedIndex].value = valueToSet;
}
To use this function, simply call it like this:
setSelectedValue(document.getElementById('strPlan'), 'selected');
For a live demonstration, you can check out this Demo
If you are looking to select an option in the dropdown based on its value, you can use the following function:
Define this function in your JavaScript:
function selectOptionByValue(selectElement, value){
var options = selectElement.options;
for(var i = 0; i < options.length; i++){
if(options[i].value === value){
selectElement.selectedIndex = i;
return true;
}
}
return false;
}
To set the option by its value, use the function like this:
selectOptionByValue(document.getElementById('strPlan'), '1');
For a demonstration, you can visit this Demo