born2gamble
born2gamble

Reputation: 207

innerHTML & accessing object property

I want to get the value of the list id. Then access the object property. For example, if egg is chosen: I want to get egg.cost ( which is 9)

However, it is coming up as undefined.

HTML portion :

<select id = "list">
<option value = "egg">Eggs</option>
<option value ="banana">Banana</option>
</select>

</select>
<button onclick ="getSelectValue()"></button>
<div id ="example">testing</div>

javascript:

function getSelectValue(){
    var selectedValue = document.getElementById("list").value;
    document.getElementById("example").innerHTML=selectedValue["cost"];
}

var banana = {
              cost:1.39,
              servings:6,
              servingSize:1,
              costPerServing:.23
              };

var egg = {
            cost:9,
            servings:24,
            servingSize:1,
            costPerServing:.38

          };

Upvotes: 0

Views: 2059

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

Create a dictionary of objects(items), and get the relevant object using the value of the <select>:

var list = document.getElementById("list");
var example = document.getElementById("example");
var items = {
  banana: {
    cost: 1.39,
    servings: 6,
    servingSize: 1,
    costPerServing: .23
  },

  egg: {
    cost: 9,
    servings: 24,
    servingSize: 1,
    costPerServing: .38

  }
};

function getSelectValue() {
  var selectedValue = list.value;
  example.innerHTML = items[selectedValue].cost;
}
<select id="list">
<option value = "egg">Eggs</option>
<option value ="banana">Banana</option>
</select>

<button onclick="getSelectValue()">Get cost</button>
<div id="example">testing</div>

Upvotes: 2

Sebastian Simon
Sebastian Simon

Reputation: 19475

That’s because selectedValue is the string "egg", not the variable egg. You’ll need to group both of your objects in another object (let’s call it foods), like so:

var foods = {
  egg: {
    // …
  },
  banana: {
    // …
  }
}

Then you can extract the values by foods[selectedValue].cost.

Upvotes: 0

Related Questions