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?
3
Answers
You can put all the variables in an object instead and dynamically access its properties based on the input.
Super simple version but you probably need more for mismatches/no matches etc.
Here I put an event listener on the input for change and then ran a comparison, only alerting when it started with the input. Try also "ac" etc.
Solution – Add an event listener to the input field, which we can then use to check for user input and display the required alert.
I have added the solution to this CodeSandbox – https://codesandbox.io/s/nostalgic-bessie-tp8vnn