0

Sorry for my English. A want to write out numbers (0, 3, 6, 9... 27) with the help of a for loop, but it seems it is harder than I thought. Thank You for your help. I found a similar problem: For loop onclick button

function count() {
  var i = 0;
  if (i < 10) {
    document.getElementById("demo").innerHTML = (i * 3);

  } else {
    document.getElementById("demo").innerHTML = "nothing";
  }
  i++;
}
<div>
  <h1>This is a Heading</h1>
  <h1 onclick="count()"><span>Click on me</span></h1> 
  <br/>
  <p id="demo"></p>
</div>

View on JSFiddle

Community
  • 1
  • 1
Zsolt Simon
  • 18
  • 1
  • 5

2 Answers2

2

If I understand correctly, I don't think you need a for loop.
Your current code defines i=0 each time the function is called.
You'll just need to define the i variable outside of your function so it can be properly incremented.

var i = 0;

function count() {
  if (i < 10) {
    document.getElementById("demo").innerHTML = (i * 3);
  } else {
    document.getElementById("demo").innerHTML = "nothing";
  }
  i++;
}
<div>
  <h1>This is a Heading</h1>
  <h1 onclick="count()"><span>Click on me</span></h1> 
  <br/>
  <p id="demo"></p>
</div>

Alternatively, increment the counter by three upon each click. Below, I'm using the ternary operator. It's saying, "if i is less than 27, add three. otherwise, set it to 'nothing'."

var i = 0,
    output = document.getElementById('output');

function increment() {
  i = i < 27 ? i + 3 : 'nothing';
  output.innerHTML = i;
}

document.getElementById('trigger').addEventListener('click', increment);
<h1 id="trigger">Click on me</h1> 
<p id="output">0</p>
showdev
  • 28,454
  • 37
  • 55
  • 73
1

How about something like that:

function count() {
  for (i=0; i<10; i++) {
    document.getElementById("demo").innerHTML += (i * 3)
  }
}
IulianP
  • 136
  • 5