[solved] specific words to make a random text appear // searchbar

Hi,
I’m trying to make a small improvement with my search bar!
I would like that when a user enters specific words (words) in the search bar (Bar) it will show a text (tryy) that is random each time.

(example:
the user enters the word: “youpi”
A text appears: " hello ".
The user repeats the operation with the same word: “youpi”
A text appears: “cool”
The user enters the word: “hi”
A text appears: “hello”
Etc… )
this code works well for one value:

let tryy = [“try1”,“try2”,“try3”]
if ($w(“#Bar”).value === “word1”) {
$w(“#text1”).text = tryy [Math.floor (Math.random () * 3)];
$w(“#text1”).show();
} else {
$w(“#text1”).hide();
}

But when I try with several values it doesn’t work:

let words = [“word1”,“word2”,“word3”]
let tryy = [“try1”,“try2”,“try3”]
if ($w(“#Bar”).value === words) {
$w(“#text1”).text = tryy [Math.floor (Math.random () * 3)];
$w(“#text1”).show();
} else {
$w(“#text1”).hide();
}

I also tried like this but it doesn’t work either:

let tryy = [“try1”,“try2”,“try3”]
if ($w(" #Bar “).value === [“word1”,“word2”,“word3”]) {
$w(”#text1").text = tryy [Math.floor (Math.random () * 3)];
$w(“#text1”).show();
} else {
$w(" #text1 ").hide();
}

Do you have any idea how to proceed?
Thanks in advance

“words” is an ARRAY with 3 values in it.
You surely wanted to compare $w(" #Bar ").value with each values in the “words”-ARRAY. You already recognized? —> EACH <----

So why not trying an “for-each-loop”, to loop trough the whole ARRAY ?

Of course you could also use a normal loop, like…

 let words = ["word1","word2","word3"]
 let tryy = ["try1","try2","try3"]

for (var i = 0, i<3, i++) {console.log(words[i])
  if ($w("#Bar").value === words[i]) {
     $w("#text1").text = tryy [Math.floor (Math.random () * 3)];
     $w("#text1").show();
  }
  else {$w("#text1").hide();}
}

@russian-dima Thanks for your support, I’m really a novice I’ll start with the simplest ! I’m interested by « forEach » I would like to learn.
I tried your code but it gives me errors, I tried to replace (var i = 0, i<3, i++) with (var i = 0; i<3; i++) but it only recognizes word3
It’s strange, maybe that’s where foreachloop would be interesting?

could you explain it to me like a child ? :slight_smile:

try doing something like:
if(words.includes($w(" #Bar ").value)){
//do your code
}

full array documentation is here: Array.prototype.includes() - JavaScript | MDN

@georgiopesenti
Explanations for every JS-command you will find here…
https://www.w3schools.com/
take a look on it.

For example: Andrew gave you another suggestion. Surely it will be some new code-lines for you. To understand Andrews or my suggestions better, you use the mentioned site and search for example for ----> “includes”.

This is my search-result —> https://www.w3schools.com/jsref/jsref_includes.asp

I just used your solution and it works, thanks ! :slight_smile:

thanks for the discovery of this website it will serve me for sure !