Senseless
Senseless

Reputation: 99

Why is the javascript function and for loop returning undefined in the dropdown menu?

I have made an HTML-form. The dropdown menus are only returning undefined. Here is the form:

 <fieldset>
    <legend>New account</legend>
    <label for="selectAccountType">Type:</label>
    <select id="selectAccountType"></select>
    <label for="txtAccountAlias">Alias:</label>
    <input type="text" id="txtAccountAlias" value="">
    <p>
      <button onclick="createAccount()">Create account</button>
    </p>
  </fieldset>

And here are the variables/object:

var EAccountTypes = {
Standard : {text: "Brukskonto"},
Saving   : {text: "Sparekonto"},
Credit   : {text: "Kredittkonto"},
Loan     : {text: "Lånekonto"}  
};

And this is the function:

  function loadAllAccountTypeKeys () {
  var keys = Object.keys(EAccountTypes);
  for (var index = 0; index < keys.length; index++) {
      var accountKey = keys[index];
      var newOption = document.createElement("option");
      newOption.value = accountKey;
      newOption.text = EAccountTypes[accountKey].name;
      selectAccountType.options.add(newOption);
  }
}

loadAllAccountTypeKeys();

Why does this give me a dropdown menu with four undefined? I have used var keys in another function in the same document. Is that the reason?

(This is a school task. I'm not actually trying to make an online bank with javascript.)

Upvotes: 0

Views: 31

Answers (1)

Kosh
Kosh

Reputation: 18423

Replace name with text here:

newOption.text = EAccountTypes[accountKey].name;

So it would look like

newOption.text = EAccountTypes[accountKey].text;

Upvotes: 2

Related Questions