Search code examples
javascriptvariablesvar

Use a variable to find another variable?


I have been working on a program involving user input via an <input> element, and wanted to do something where depending on what they typed, it changed a different variable, with something like this:

var input = document.getElementById('myInput').value;
var a = "ac";
var b = "bc";
var c = "cc";
alert(input)//Where input is replaced once ran with what is inputed, so if a is typed it alerts "ac"
<input id="myInput" type="text" value="a" />

Obviously, the above example does not work, but is there a way where it would?


Solution

  • You can put all the variables in an object instead and dynamically access its properties based on the input.

    const obj = {
      a: "ac",
      b: "bc",
      c: "cc"
    };
    document.querySelector('button').addEventListener('click', e => {
      const val = document.getElementById('myInput').value;
      console.log(obj[val]);
    });
    <input id="myInput" type="text" value="a" />
    <button>Get value</button>