2

I'm trying to print the same repetitive piece of text over and over (\I[0]), but with the number inside it incrementing by 1 each time (ex: \I[0] \I[1] \I[2] etc). I've figured that out already.

But what I want to do is make it so every time the piece of text is printed 15 times, it will add a line break.

EX: Prints 0 - 14. Then, puts in a <br> tag, and keeps printing, until it reaches 29. Then, adds another <br> tag. Etc. until it reaches the number 527.

HTML:

<p id="number"></p>

Javascript:

var text = "";
var i;
for (i = 0; i < 528; i++) {
    text += "\\I[" + i + "] ";
}
document.getElementById("number").innerHTML = text;

Any ideas? Thank you.

samfortunato
  • 43
  • 2
  • 8

4 Answers4

1

You could check if the number is a factor of 15 and use modulo operator to insert a new line.

var text = "";
var i;
var MAX = 528;
for (i = 0; i < MAX; i++) {
    text += "\\I[" + i + "] ";
    
    if(i !==0 && ((i + 1 < MAX) && ((i + 1) % 15 === 0))) {
        text += '<br>';
    }
}
document.getElementById("number").innerHTML = text;
<div id="number">
 
</div>
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • The thing is, this would display numbers 0 - 15. That's 16 numbers on the first line. There's 15 on the subsequent lines, but everything's off, as the first line has too many numbers. Thanks, though. – samfortunato Apr 11 '17 at 17:38
  • @sfor You could tweak the condition a bit and get the expected result. Check the updated post. – Sushanth -- Apr 11 '17 at 17:53
0

If I get your question right, you can use a modulo (rest of the division) for that :

var text = "";
var i;
for (i = 0; i < 528; i++) {
    text += "\\I[" + i + "] ";
    if (i!=0 && i%15==0)
        text+="<br/>";
}
document.getElementById("number").innerHTML = text;
Nico_
  • 1,388
  • 17
  • 31
0

You could use a ternary expression and add either an empty string or a break.

var text = "",
    i;

for (i = 0; i < 528; i++) {
    text += (i % 15 || !i ? '': '<br>') + "\\I[" + i + "] " ;
}

document.getElementById("number").innerHTML = text;
<p id="number"></p>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

     var text = "";
    var i;
    var count = 0;
    
    for (i = 0; i < 528; i++) {
    text += "\\I[" + i + "] ";
    count = count + 1;
    if(count % 15 == 0)
    {
    text +="<br/>";
    }    
    }

document.getElementById("number").innerHTML = text;
  <p id="number"></p>