0

I would like to instantly print the user input from a prompt in a loop on a div element of id=results . However, the prompt runs 6 times continuously and then all the inputs are printed in the div. I want each input to be printed on div one at a time after each prompt input.

for (let i = 0; i < 7; i++) {
  var x = parseInt(prompt("Enter a number"));
  h1 = document.createElement('h1');
  var result = document.createTextNode('Your inputs are: ' + x);
  h1.appendChild(result);
  document.getElementById('results').appendChild(h1);
}
<div id="results"></div>

7
  • what does not work ? what error ? Commented Jun 3, 2020 at 13:21
  • Have you tried .forEach instead of a for loop? Commented Jun 3, 2020 at 13:21
  • @MichaelMishin The prompt box pops up six times in a row and then inputs are printed on the div element. I want each input print to happen after every prompt. Commented Jun 3, 2020 at 13:26
  • Do you want to print everything at once after six prompt? Commented Jun 3, 2020 at 13:28
  • @MichaelMishin No, I want print 1 to happen after prompt 1, print 2 to happen after prompt 2 till print 7 after prompt 7. Commented Jun 3, 2020 at 13:29

1 Answer 1

2

prompt and alert are blocking.

Give the interface time to update the DOM

Try this instead:

let cnt = 7;
const addNum = () => {
  let x = parseInt(prompt("Enter a number"));
  h1 = document.createElement('h1');
  let result = document.createTextNode('Your inputs are: ' + x);
  h1.appendChild(result);
  document.getElementById('results').appendChild(h1);
  cnt--;
  if (cnt > 0) setTimeout(addNum,100);
};
addNum();
<div id="results"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.