Search code examples
javascriptdom-events

JavaScript selecting from list


I'm stuck with a weird issue!

I have this code:

<script>
  window.PRICES = {
    'Gold' : { 10: 299, 20: 400, 100: 1745, },
    'Coins': { 10: 300, 40: 355, 1000: 30000, },
  };
</script>
<script>
function pick(i,n) {
  document.getElementById("Item").innerHTML = i+" "+n;
  document.getElementById("Price").innerHTML = (window.PRICES)[i][n];
}
</script>

The function pick is called by a select's onchange event:

<select name="Gold" onchange="pick(this.value,this.name)">
  <option value="10">10 Gold</option>
  <option value="20">20 Gold</option>
  <option value="100">100 Gold</option>
</select>

But when I change the value I get:

"Uncaught TypeError: Cannot read property 'Gold' of undefined"

BUT window.PRICES isn't UNDEFINED! Whats wrong?

PS: I'm able to call pick('Gold','10') using GC console!


Solution

  • The order of the arguments of your onchange handler is switched. It should be pick(this.name, this.value), since you are accessing the PRICES object first by name, and only then by value, just like in your example pick('Gold', '10').