1

I am trying to make a simple program that allows me to check input of a form is a valid "command" and send "return";

However, my code doesn't work. Can someone please help me? The problem is that even when I type help or ping it thinks it's incorrect and does the alert and location.reload(); HTML:

const commands = [{
    command: 'help',
    return: 'there is no help'
  },
  {
    command: 'ping',
    return: 'pong lol'
  },
];

function sendCommand(x) {
  var commandReturn = document.getElementById("commandReturn");
  if (commands.includes(x) == true) {
    let returnable = commands.includes(x).return;
    commandReturn.innerHTML += (returnable + "<br>");
  } else {
    console.log("Incorrect command, restarting...")
    location.reload();
  }
}
<div id="commandReturn">
</div>
<form onSubmit='document.getElementById("input").value=""; sendCommand(this);'>
  <input method="post" name="command" placeholder="_" id="input">
</form>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Neon Foxer
  • 17
  • 6
  • I made you a snippet. Please change it to a [mcve] – mplungjan Mar 28 '21 at 09:33
  • You can use `.find()` to find the object in your array with the `command` equal to `x`. The `.includes()` method just returns true/false if the literal value `x` is in your array, and since your array consist of objects, `x` would need to be the same reference to the object in your array for it to return `true`. See [Find object by id in an array of JavaScript objects](https://stackoverflow.com/q/7364150) – Nick Parsons Mar 28 '21 at 09:42

2 Answers2

0

Here is a working version.

  • You needed to get x
  • Inputs do not have methods
  • Use addEventListener so you can cancel the submission

I use an optional chaining operator to not have too many ifs

const commands = [{
    command: 'help',
    return: 'there is no help'
  },
  {
    command: 'ping',
    return: 'pong lol'
  },
];

document.getElementById("commandForm").addEventListener("submit", function(e) {
  e.preventDefault()
  let commandReturn = document.getElementById("commandReturn");
  const x = document.getElementById("input").value;
  document.getElementById("input").value = "";
  const retValue = commands.filter(item => item.command == x)?.[0]?.return; // optional chaining, if nothing returned  
  commandReturn.textContent = retValue ? retValue : "Incorrect command, restarting..."
 // if (!retValue) location.reload();

});
<div id="commandReturn">
</div>
<form id="commandForm">
  <input name="command" placeholder="_" id="input">
</form>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

1 you have array of Object, not String

2 let returnable = commands.includes(x) it returns you boolean true or false