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>
1
  • 1
    You shouldn't repeat document.getElementById("stateSelect"). Call it once and store the reference in a variable. Commented Apr 15, 2011 at 14:42

3 Answers 3

51

Change the line that reads:

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

to:

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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;
            }
        }
...

Comments

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
      }
    })
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.