I have a dropdown menu and I cannot figure out how to make a javascript function select a drop down menu option. I have tested the output of the variables and they are all correct, but it still will not select the option when clicked. Here is the function and drop down menu.
Function
function formFill(a, b, c){
theform.from.value = a;
theform.to.value = b;
for(var i = 0;i < document.getElementById("stateSelect").length;i++){
if(document.getElementById("stateSelect").options[i].value == c ){
document.getElementById("stateSelect").selected = true;
}
}
}
Menu item
<select id="stateSelect" name="stateSelect">
<option value="none">(None)</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
3 Answers 3
Change the line that reads:
document.getElementById("stateSelect").selected = true;
to:
document.getElementById("stateSelect").selectedIndex = i;
1 Comment
Alt. you can set selected to the actual option: select.options[i].selected = true;
...
var select = document.getElementById("stateSelect");
for(var i = 0;i < select.options.length;i++){
if(select.options[i].value == c ){
select.options[i].selected = true;
}
}
...
Comments
With Stimulus, for instance we fetch the user's time zone and then we auto-select it in the dropdown
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["input"]
connect() {
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
[...this.inputTarget.options].forEach((option) => {
if (option.value == timeZone) {
option.selected = true
}
})
}
}
document.getElementById("stateSelect"). Call it once and store the reference in a variable.