Select dropdown menu option with javascript
Asked Answered
D

3

36

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>
Delvalle answered 15/4, 2011 at 14:26 Comment(1)
You shouldn't repeat document.getElementById("stateSelect"). Call it once and store the reference in a variable.Sieber
G
50

Change the line that reads:

document.getElementById("stateSelect").selected = true;

to:

document.getElementById("stateSelect").selectedIndex = i;

Garton answered 15/4, 2011 at 14:32 Comment(1)
Because it needs to know which item to select. .selected is a get() that gets the state of selected/not selected, but cannot set the state because it does not know which item to select.Reversioner
A
20

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;
            }
        }
...
Alexandra answered 15/4, 2011 at 14:47 Comment(0)
B
0

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
      }
    })
  }
}
Bailsman answered 9/2 at 9:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.