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

Time:12-04

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--
    }

CodePudding user response:

You completely misunderstood Javascript. The initial code looks like rubbish.

Is the code below what you want to achieve?

alert('You`ll be prompted to specify how many times to repeat the cycle.');
const value = document.getElementById('count')?.value || 1;

const numOfRuns = confirm(`As many as this: ${value}`) ? value : (new Number(prompt('How many times to repeat the cycle?')));

for (let i = 0; i < numOfRuns; i  ) {
  document.write('Welcome to my page!<br>');
}

CodePudding user response:

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();
  • Related