1

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.

4
  • 2
    isn't i < number ? Since you already specified that var i = 0. Also, instantiate the variable myHTML before the loop Commented Mar 5, 2020 at 12:27
  • 1
    You get an error in your script because you're using the undeclared variable myHTML Commented Mar 5, 2020 at 12:27
  • Also, as @CalvinNunes mentions, the exit condition for the loop is wrong - it will not terminate. Commented Mar 5, 2020 at 12:28
  • so how do i make it right? i have changed the i < number part Commented Mar 5, 2020 at 12:29

1 Answer 1

2

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>

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

1 Comment

thank you very much, i see now. im such a beginner in coding so i appreciate this a lot

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.