Fishy guy
Fishy guy

Reputation: 11

Javascript input run a function when specific text is typed in

So I would like to run a function when a user inputs a certain command in the input box. For example, when a user types something like 'I want an ice cream sandwich' it would run a function that would add 1 ice cream sandwich to their inventory. But if they typed something like 'Gerfabujohn' it would tell you thats not a command. I have already got the function that adds the sandwich to the inventory done, that's not the problem. Heres my js:

function readCommand() {
  let readInput = document.querySelector('#commandInput').value
  if (readInput.value = 'I want an ice cream sandwich') {
    giveIceCreamSandwich()
  } else {
    alert(`Not a command`);
  }
}

and my html:

<label for="commandFeild"> Enter Command: </label>
<input type="text" id="commandInput" name="commandFeild"><br><br>
<button class="triggerInput" onclick="readCommand()"> Run Command </button>

Here I am trying to use the querySelector function to find the value of the input box using it's id. So far, this part seems to work. I used console.log to log the value of readInput and it logged the correct command from the input field. It's the if statement that does not work at all. Apparently, no matter what I type in, it returns true and runs the function anyways, oblivious to the conditions that need to be met for it to be true.

I have been searching for hours for a solution, and I'm really surprised I didn't find an answer as this seems to be the main function of the input statement in the first place. Any help would be appreciated, thanks!

Upvotes: 0

Views: 91

Answers (1)

chazsolo
chazsolo

Reputation: 8439

Two issues:

  1. = is for assignment not equality checking - you want to use ===.
  2. You are storing the value of the input into readInput, so you don't need to reference value from it:
function readCommand() {
  let readInput = document.querySelector('#commandInput').value
  //           ↓ no .value, it's already here -----------↑
  if (readInput === 'I want an ice cream sandwich') {
  //             ↑ === vs =
    giveIceCreamSandwich()
  } else {
    alert(`Not a command`);
  }
}

Upvotes: 2

Related Questions