Frsti Frsti - 1 month ago 4
Javascript Question

Is it possible to echo a variable value in an array reference

I need to pull the value of an input by class and then "echo" or reference that value in an associative array

So far my javascript looks like:

var phone_code = document.getElementsByClassName( 'model' ).value;
var phone = [];
phone["6s"] = "23.52";
phone["5s"] = "9.88";
phone["5Se"] = "14.59";
phone["7"] = "28.49";
phone["s7e"] = "27.49";
phone["s7"] = "23.52";
phone["s6e"] = "21.04";
phone["s6"] = "18.56";
phone["a5"] = "12.61";
phone["j5"] = "7.65";
phone["a3"] = "8.64";
phone["j3"] = "5.17";
phone["p9"] = "16.08";
phone["p9lite"] = "8.64";

document.getElementById("phone-cost").innerHTML = phone[phone_code]


And the array output is:

Your Phone would cost you £<span id="phone-cost"></span> per month


However, the output just reads "undefined" so I'm not sure if the javascript is the problem or I need to look further back in the process

phone_code needs to use class as it pulls from an dropdown that is enabled/disabled by the form, whichever dropdown is enabled needs to be used. I think my problem is that

phone[phone_code]


isn't how I should be referencing the variable but I can't find a specific answer on the right way to format within an array

Thanks

Answer

Two things:

(1) .getElementsByClassName() returns an array-like object of elements, not a single element.
(2) While it is possible to use an array the way you are in your code, it's far better to use a plain object.

See below:

var btn = document.getElementById('getPrice');

btn.addEventListener('click', function() {
  var phone_code = document.getElementsByClassName('model')[0].value;

  var phone = {};
  phone["6s"] = "23.52";
  phone["5s"] = "9.88";
  phone["5Se"] = "14.59";
  phone["7"] = "28.49";
  phone["s7e"] = "27.49";
  phone["s7"] = "23.52";
  phone["s6e"] = "21.04";
  phone["s6"] = "18.56";
  phone["a5"] = "12.61";
  phone["j5"] = "7.65";
  phone["a3"] = "8.64";
  phone["j3"] = "5.17";
  phone["p9"] = "16.08";
  phone["p9lite"] = "8.64";

  document.getElementById("phone-cost").innerHTML = phone[phone_code];
});
<select class="model">
  <option value="6s">6s</option>
  <option value="5s">5s</option>
  <option value="5Se">5Se</option>
</select>
<input type="button" value="Get Price" id="getPrice" />Your Phone would cost you £<span id="phone-cost"></span> per month