How do you create a for loop using a variable in javascript?

katekatekate :

I have a block of code under a div element "questionform" and want to allow the code to repeat, depending on the number of times the user would like it to, to eventually allow the user to make a quiz. I have tried to create a bit of javascript in order to repeat just the question number for now, but it won't work.

<div id="myHTMLWrapper">

</div>

<script>
  var wrapper = document.getElementById("myHTMLWrapper");

  var number = prompt("Enter the number of questions");

  for (var i = 0; i = number - 1; i++) {
    myHTML += '<span class="test">Question' + (i + 1) + '</span><br/><br/>';
  }

  wrapper.innerHTML = myHTML

</script>

any help will be appreciated, and please dont just point out flaws and not tell me how to improve them.

Mamun :

You have two issues in your code. firstly, you have to declare the variable myHTML outside the loop with empty string. Secondly, in the loop i = number - 1 will prevent the iteration of the loop, try i < number

<div id="myHTMLWrapper">

</div>

<script>
  var wrapper = document.getElementById("myHTMLWrapper");

  var number = prompt("Enter the number of questions");
  var myHTML = '';
  for (var i = 0; i < number; i++) {
    myHTML += '<span class="test">Question ' + (i + 1) + '</span><br/><br/>';
  }

  wrapper.innerHTML = myHTML;

</script>

Though, here starting the loop iteration value from 1 with i <= number is more meaningful as this will allow you to use the value directly (without the increment) in the htmlString:

<div id="myHTMLWrapper">

</div>

<script>
  var wrapper = document.getElementById("myHTMLWrapper");

  var number = prompt("Enter the number of questions");
  var myHTML = '';
  for (var i = 1; i <= number; i++) {
    myHTML += '<span class="test">Question ' + i + '</span><br/><br/>';
  }

  wrapper.innerHTML = myHTML

</script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29850&siteId=1