1

Why does this JS not work? The goal is to enter something into the text box that isn't help, windows-xp, explicit, default, or nothing, press enter, and have that alert "Command doesn't exist".

function checkInput() {
  var commandInput = document.getElementById("command-input")

  if (commandInput.value !== "help", "windows-xp", "explicit", "default", "") {
    alert("Command doesn't exist.");
  }

  event.preventDefault();

  document.getElementById("command-form").reset();
}
<form id="command-form">
  <input type="text" placeholder="Enter Command" id="command-input">
  <input type="submit" onclick="checkInput();" style="display: none;">
</form>
Akshay Mulgavkar
  • 1,727
  • 9
  • 22
  • you have to compare each string to commandInput.Value, you can't just say !== on the first one. You could also just put all these in string array and use an array function to iterate through them. – Alejandro Feb 18 '20 at 03:12

2 Answers2

2

Use Array.includes:

const validCommands = ["help", "windows-xp", "explicit", "default", ""];

if (!validCommands.includes(commandInput.value)) {
  alert("Command doesn't exist.");
}
Josh Wulf
  • 4,727
  • 2
  • 20
  • 34
1

Make an array (or Set) of the strings you want to permit, then check if the array .includes the value:

function checkInput(event) {
  event.preventDefault();
  const commands = ["help", "windows-xp", "explicit", "default", ""];
  const { value } = document.getElementById("command-input");
  if (!commands.includes(value)) {
    console.log('Command doesnt exist ');
    return;
  }
  console.log('Carrying out command', value);
  commandForm.reset();
}
const commandForm = document.getElementById("command-form");
commandForm.addEventListener('submit', checkInput);
<form id="command-form">
    <input type="text" placeholder="Enter Command" id="command-input">
    <input type="submit">
</form>

Also note that you should avoid inline handlers whenever possible, they have too many gotchas, require global pollution, and are bad practice - attach event listeners properly using Javascript instead, like in the above snippet.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320