Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A repeating document.write that asks how many times to repeat

Faced a problem. On the site, i need to generate such a number of certain lines (via document.write("Welcome to my page") ) that the user will tell through the dialog box, when dialog box opening on the page. All this happens through <script> … </script>. I tried it in different ways, but nothing works. Help me, please.

 confirm("Specify how many times to repeat?');
 var run() = promt("How many times? {value}') 
function run(){
     let value = document.getElementById('count').value
     if(confirm(Run block ${value} times?)) {
        while(value < 0){
            document.write(Welcome to my page!<br>')}
     }
}

A friend suggested this, but it doesn’t work either.

 let res = prompt('How many times?',1)
    if(!res || isNaN(Number(res)) || res < 0) {
        alert('Invalid quantity entered')
        location.reload()
return
    }
    res = Math.round(Number(res))
    while (res > 0){
        document.write(`Welcome to my page!<br>')}
        res--
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is a simple solution to your problem. First, you can use the prompt() function to ask the user how many times they want to repeat the line. You can then use a for loop to repeat the line the specified number of times. Here is an example

function run() {
  // Ask the user how many times to repeat the line
  let count = prompt("How many times should I repeat the line?");

  // Make sure the input is a number
  if (!count || isNaN(Number(count)) || count < 0) {
    alert("Invalid quantity entered");
    return;
  }

  // Convert the input to a number and round it to the nearest integer
  count = Math.round(Number(count));

  // Use a for loop to repeat the line the specified number of times
  for (let i = 0; i < count; i++) {
    document.write("Welcome to my page!<br>");
  }
}

You can call this function when the page loads by adding the following code inside a tag:

run();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading