0

So i have some simple javascript code and i want to check if the input of the user is equal to any of the items in the "options" array, i tried this method but it isn't working, does anyone know why/another way to do this?

var options = ["fris", "bier", "wijn"];
var bestelling_opgenomen = false;


var bestelling = prompt("Welke bestelling wilt u toevoegen?");

if(options.includes(bestelling) == bestelling){
    var hoeveelheid = prompt(`hoeveel ${bestelling} wilt u bestellen?`);
}else{
    alert("kurk");
}
  • 6
    [`.includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) returns `true`/`false` depending if the item is, well, included. So `if(options.includes(bestelling)) {` – Gabriele Petrioli Nov 12 '20 at 22:44
  • 4
    Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – A. Meshu Nov 12 '20 at 22:47

2 Answers2

2

.includes returns a boolean. So you're just using it wrong.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Try

var options = ["fris", "bier", "wijn"];
var bestelling_opgenomen = false;


var bestelling = prompt("Welke bestelling wilt u toevoegen?");

if(options.includes(bestelling)){
    var hoeveelheid = prompt(`hoeveel ${bestelling} wilt u bestellen?`);
}else{
    alert("kurk");
}

You might also want to lowercase the input just to make sure the user didn't type in a name with capitals.

user101289
  • 9,888
  • 15
  • 81
  • 148
0
if(options.indexOf(bestelling) > -1)
Great Coder
  • 397
  • 3
  • 14