skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. 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.

    function checkStartsWith(value, arrayValue) {
      return arrayValue.startsWith(value);
    }
    document.getElementById('myInput')
      .addEventListener('change', function(event) {
        let inputValue = this.value;
        const values = [
          "ac", "bc", "cc"
        ];
        values.forEach((element) => {
          let hasValue = checkStartsWith(inputValue, element);
          console.log(hasValue, element);
          if (hasValue) {
            alert(element);
          }
        });
      });
    <input id="myInput" type="text" /> enter something
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search