Search code examples
javascriptjavascript-objectsdropdown

Selecting value of an object based on value of dropdown field


Codepen: https://codepen.io/moarpie/pen/EBKVBL

I'm trying to do two things in this project:

  • Display text based on selector value
  • Get value from input field and modify by value of an object based on selection from dropdown

The first part I have accomplished, but I am having trouble getting the second part to work.

Example: If bear is selected from dropdown, I want to output bear.weight and if puma is selected I want to output puma.weight.

So instead of

var outputValue = (parseInt(userInput) / parseInt(puma.weight)) * 100;

The parseInt(puma.weight) should should be whatever value is selected in the dropdown.

I've gotten this to work by just using if statements but of course this isn't best practice and becomes tedious if I have 100 objects to choose from.


Solution

  • Inside the click event callBack function, you can get a string from the currently selected option using

    var selectedAnimal = document.getElementById('animalSelector').value;
    

    This will return e.g. puma

    To get the weight value from it's associated object (var puma = {name:"pumaName", weight:500};) you can use

    eval(selectedAnimal).weight
    

    So for example

    var outputValue = (parseInt(userInput) / parseInt(eval(selectedAnimal).weight)) * 100;