Home Need two variables to assume different values based on one user input
Reply: 1

Need two variables to assume different values based on one user input

Creebles
1#
Creebles Published in 2018-02-12 17:54:03Z
var Item = document.getElementById('Item').value;
var ItemWeight;
var ItemPrice;

//Items weight
var Wfirst = 1;
var Wsecond = 2;
var Wthird = 3;

//Items price
var Pfirst = 10;
var Psecond = 20;
var Pthird = 30;

I need ItemWeight and ItemPrice to assume the values of, respectively, weight and price listed in the code, based on the Item selected in input by the user.

As I have a list of over 20 different items, how could I do it in an efficient way?

I'm new to JS so thank you in advance for the help

freginold
2#
freginold Reply to 2018-02-12 18:02:39Z

An easy way to do this would be to use an array to store your weights and prices. That way you can reference the correct weight and price based on the item number (which would be the array index).

See this example:

var Item = document.getElementById('Item').value;
var ItemWeight;
var ItemPrice;

//Items weight
var W = [
  1,
  2,
  3
]

//Items price
var P = [
  10,
  20,
  30
]

ItemWeight = W[parseInt(Item)];
ItemPrice = P[parseInt(Item)];
console.log("Weight: " + ItemWeight + "\nPrice: " + ItemPrice);
Item:
<input id="Item" value=1 />

You could also organize your weights and prices using an array of objects, with properties such as item[1].weight and item[1].price.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.528967 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO