How to select a value in a select dropdown with JavaScript?
Use the selectedIndex
property:
document.getElementById("Mobility").selectedIndex = 12; //Option 10
Alternate method:
Loop through each value:
//Get select object
var objSelect = document.getElementById("Mobility");
//Set selected
setSelectedValue(objSelect, "10");
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
easiest way is to just use this
document.getElementById("mySelect").value = "banana";
myselect is name of your dropdown banana is just one of items in your dropdown list
function setSelectedIndex(s, v) {
for ( var i = 0; i < s.options.length; i++ ) {
if ( s.options[i].value == v ) {
s.options[i].selected = true;
return;
}
}
}
Where s is the dropdown and v is the value
The simplest possible solution if you know the value
document.querySelector('option[value=" + value +"]').selected = true