0

Inside of a function I'm getting a value from an input box, like this.

    var $value = $('#inputid').val().toLowerCase();

So I want to have the returned variable $value be used to call another variable. Above that code is a variable declaration.

    var $somethingA = "1";
    var $somethingB = "2";

If the user types in "somethingA" I want to get an alert that says "1". Is this possible?

Sorry if it is a silly question. Thanks!

Dropoff510
  • 51
  • 2
  • 7
  • 1
    possible duplicate of [Javascript dynamic variable name](http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name) – Fabrício Matté Nov 16 '13 at 21:54

1 Answers1

1

That's possible, but you need to use an object as a map rather than multiple variables to hold your values.

var inputMap = {
    somethingA: 1,
    somethingB: 2
};

var input = $('#inputid').val().toLowerCase();

alert(inputMap[input]);

Note that if you were in the global scope (which would be a bad practice) you could just get the same effect by accesing variables using window[someDynamicProperty], since global variables are properties of the window object in a browser environment.

plalx
  • 42,889
  • 6
  • 74
  • 90