Create menu inside an Alert() with repeat loop

Asked

Viewed 103 times

1

I am trying to create a menu of options for the user to choose one of the 20 previous exercises to open in the browser. Only instead of creating it manually, I use the repeating structure for with two variables x and i to create this menu automatically. But I wanted to put this text generated by the loop inside a dialog box alert(texto). I have tried in many ways, but none of them have succeeded.

First attempt

var x;
var i = 38;
for (x = 0; x < 20; x++) {
  texto = (x+1) + "- Exercício" +(i++)+ "\n";
}
var menu = parseInt(prompt(texto));

2nd Attempt

var x; 
var i = 28;
document.write("<div id='menu'>");
for (x = 0; x <= 20; x++) {
  document.write((x+1) + "- Exercício" +(i++)+ "<br>");
}
document.write("</div>");
var texto = document.getElementById('menu');
var alert(texto);

Third attempt

var x;
var i = 38;
alert("Escolha um exercício para abrir:");
for (x = 0; x < 20; x++) {
  var menu = parseInt(prompt((x+1) + "- Exercício " +(i++)+ "\n"));
}

Question: It is possible to create this large menu within a dialog box using only a repeat loop?
Obs. I’m just starting to assemble it, and if any information is missing, don’t disregard this question. :-'

1 answer

3


It is possible to create this large menu within a dialog box using only a repeat loop?

Quick response: nay.

The alert does not work as a checkbox. If you create a loop that calls for alerts (alert) or dialogue boxes (such as prompt), one will be called after the other, see:

// Note que assim que você fechar uma alerta,
// outra aparecerá logo em seguida, até chegar
// na décima (e final) iteração.
for (let i = 1; i <= 10; i++) {
  alert(`Exercício ${i}`);
}

I suppose what you need to create is a checkbox:

// Criamos um menu de seleção:
const select = document.createElement('select');

// A cada iteração, adicionamos mais uma
// opção ao menu de seleção (criado acima):
for (let i = 1; i <= 10; i++) {
  const option = document.createElement('option');
  option.value = i;
  option.textContent = `Exercício ${i}`;
  select.appendChild(option);
}

// Criamos um listener de evento para saber
// quando um exercício for selecionado:
select.addEventListener('change', (event) => {
  console.log(`Exercício selecionado: ${event.target.value}`);
});

// Adicionamos o menu de seleção ao <body>:
document.body.appendChild(select);

If you want something else in the format of alert, and not a selection menu, as demonstrated, I suggest you take a look at libraries like the Sweetalert2.

Reference:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.