prompt
is unfortunately the closest equivalent, but you have asked for an alternative - browsers don't provide a mechanism to 'wait' in the way that c
does so there's no direct equivalent.
The standard solution to this problem (a sequence of questions) in the browser would be a form, with multiple questions and answers and their own input
fields.
You could unhide subsequent input
fields as an effect of the previous field being validated.
To have, specifically, a single input that answers multiple questions, you will have to code your own solution.
Here's one way. I'm not sanitising the user input here - you'd want to do that if it were in production.
const input = document.getElementById('input');
const title = document.getElementById('title');
const resultsText = document.getElementById('resultsText');
const results = [];
let currentQuestion = "What is your name?";
const questions = [
"What country do you live in?",
"What is your primary language?"
]
const advanceForm = () => {
results.push({
q: currentQuestion,
a: input.value
})
// Wipe input
input.value = "";
// Add next question
title.innerHTML=questions[0];
currentQuestion = questions[0];
// If the questions array is not empty
if (questions.length){
// Save current input value to object
questions.shift()
} else {
// If no question left, hide input and show info instead
//Hide ID field
input.style.visibility = "hidden";
title.innerHTML = "Results:"
// Represent the results as HTML
const resultsAsHtml = results.map((result) => {
return `<p>Question: ${result.q}</p><p>Answer: ${result.a}`
})
resultsText.innerHTML = resultsAsHtml
}
}
input.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
advanceForm();
}
});
<h3 id="title">What is your name?</h3>
<input type="text" id="input">
<p id="resultsText"><p>