1

So I'm trying to make a if statement with many possibilities, but what ended up happening is now I have WAY too many || in my if.

I thought maybe it would be possible to throw all of the possible values into a array, and then only do condition == array or something.

Anyway here's my code. Please help. Thanks in advance.

<body>
<input id="userInput">
<button onclick="Submit()">Submit</button>
<script>
function Submit() {
var input = document.getElementById("userInput").value;

if (input == "random text" || input == 3 || input == "more random text" 
|| input == false || input == "another random string.")
{
  // Do Something
}
</script>
</body>
VinceKaj
  • 335
  • 4
  • 13
  • 1
    Getting familiar with [Array.prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype) might help? – Teemu Apr 09 '18 at 11:45
  • `typeof input` will always be `"string"`. You'll never get array or boolean or anything else. – Jeremy Thille Apr 09 '18 at 11:45
  • You can check for `indexOf` https://www.w3schools.com/jsref/jsref_indexof.asp – Irfan Apr 09 '18 at 11:47
  • Very similar: https://stackoverflow.com/questions/5864408/javascript-is-in-array – Takit Isy Apr 09 '18 at 12:36

1 Answers1

3

You can use Array#includes or Array#indexOf and check wether the input is included in your array where you whitelist allowed strings (or other types - depending on your input type)

Demo with includes

let arr = ['random text', '3', 'more random test', 'lorem ipsum'];

function submit() {
  input = document.getElementById("userInput").value;
  if(arr.includes(input)) {
    alert('yaaay that was easy');
  }
}
<input id="userInput">
<button onclick="submit()">Submit</button>
Kristianmitk
  • 4,528
  • 5
  • 26
  • 46