First, the objects that will be responsible for manipulating the DOM and word list:
const form = document.getElementById("procurar-form");
const input = form.getElementsByTagName("input")[0];
const button = document.getElementById("button_procurar");
const palavras = ["Papel", "Vidro", "Lata", "Terra", "etc"];
Second, we need to write a function that generates a random value, update the word within the field and run the click of the button (the latter was asked in comments). For this, we do:
function novaPalavra() {
// Gera um valor aleatório de 0 ao comprimento da lista de palavras:
const index = Math.floor(Math.random() * palavras.length);
// Atualiza o valor do campo para a palavra sorteada:
input.value = palavras[index];
// Executa o clique do botão:
button.click();
}
This function does what you want, but you have also been asked to run this code every 5 minutes. To do this, we can use the tool setInterval
, which receives the name of a function and the range that it will be executed in milliseconds. For a 5-minute interval, we need a range of 5 * 60 * 1000 milliseconds. So:
setInterval(novaPalavra, 5*60*1000);
In this way, every five minutes the word in the field will be changed to another at random and clicking the button will run.
See working:
const form = document.getElementById("procurar-form");
const input = form.getElementsByTagName("input")[0];
const button = document.getElementById("button_procurar");
const palavras = ["Papel", "Vidro", "Lata", "Terra", "etc"];
function novaPalavra() {
const index = Math.floor(Math.random() * palavras.length);
input.value = palavras[index];
button.click();
}
setInterval(novaPalavra, 1000);
<form id="procurar-form" method="get" action="Site">
<input type="text" class="procurar-field" placeholder="Vamos Procurar?" name="q" value="verde">
<button class="procurar-btn" id="button_procurar">Procurar</button>
</form>
Since the click of the button will submit the form by refreshing the page - or redirecting the user - makes no sense to have a code that run every 5 minutes, as always in his first run it will stop due to submission the form. The answer was given in this way by the author's insistence on the comments.