Antonio Salazar
Antonio Salazar

Reputation: 3

When printing in a div using innerHTML I only see the last option

I'm new to programming so the question may be a little simple for most of the users, here's my question:

I want to use innerHTML to send info to a div tag that I have in my HTML

    <div> 
            <input type="number" id="numberBox1">
    </div>
    <div id="display"></div> //I want the info to print inside this div

This is my JS code:

function asterisks(){
var line= 0 ;
var sum = "" ;
line= parseFloat(document.getElementById("numberBox1").value);

for (var i = 1; i <= line; i++) {
    sum += "*";
    console.log(sum);
}
document.getElementById("display").innerHTML += sum;
}   

This is the basic ladder of asterisks that you may already know, using the: console.log(sum); In the console I, in fact see the next: (supposing a ladder of 5 asterisks)

*
**
***
****
*****

But in the div in my html I only see the last row, I mean:

*****

At this moment I already understood that what its happening is that the information is in fact printing just that it changes so fast that I only get to see the last line...why is happening this? Any help/ideas/comments will be much appreciated,

Thanks.

Upvotes: 0

Views: 241

Answers (2)

Risheekant Vishwakarma
Risheekant Vishwakarma

Reputation: 1046

You can use append in place of innerHTML which will concatenate all your output.

Upvotes: 0

Chirag Patel
Chirag Patel

Reputation: 1642

You have to do something like this.

function asterisks(){
var line= 0 ;
var sum = "" ;
line= parseFloat(document.getElementById("numberBox1").value);

for (var i = 1; i <= line; i++) {
    sum += "*";
    console.log(sum);
    document.getElementById("display").innerHTML += sum + "<br/>";
}
}   
<div> 
        <form>
            <input type="number" id="numberBox1">
            <input type="button" id="submit" onclick="asterisks()" value="submit">
        </form>
    </div>
    <div id="display"></div> //I want the info to print inside this div

Upvotes: 4

Related Questions