Reputation: 21
Codepen: https://codepen.io/moarpie/pen/EBKVBL
I'm trying to do two things in this project:
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.
Upvotes: 0
Views: 52
Reputation: 119
you can create an object with name of weight and define the value for all dropdown value like if you have value in dropdown
<select id="animal">
<option value="bear">bear</option>
<option value="puma">puma</option>
</select>
then object must be like weight = {'bear': 150, 'puma': 200};
now suppose you get puma from your dropdown then
let output = parseInt(userInput) /parseInt(weight[document.querySelector( "#animal option:selected" ).value]) * 100
Upvotes: 1
Reputation: 12891
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;
Upvotes: 1