Alrick
Alrick

Reputation: 91

How to display Javascript function in an HTML tag?

I am trying to create a counting table for kids. I want to display a button which will display the counting in a list. I can get it to print to the page but i want to print it in paragraph tag in my HTML please have a look and suggest me the solution.

<p id="main"></p>
<button onclick="counting();" >Counting 1 to 10</button>

var counting = function(){
    var myCount = 1;
    while(myCount < 11){
    var countTotal = myCount;
    document.getElementById('main').innerHTML = countTotal;
    //print(countTotal);
    myCount++;
    }
return countTotal;
}

Upvotes: 0

Views: 104

Answers (2)

Frogmouth
Frogmouth

Reputation: 1818

The @Lal's answer is the answer (I wrote the same in a comment).

But, I suggest another way:

Instead of using the while cycle you can use a setInterval, in my opinion to create a counting table for kids the user experience is more important then performance:

take a look to this code:

var counting = function(){
    var myCount = 1;
    document.getElementById('main').innerHTML += myCount + "<br/>";
    var _timeout = setInterval(function(){
        myCount++;
        document.getElementById('main').innerHTML += myCount + "<br/>";
        if(myCount == 10) clearTimeout(_timeout)
    },1000)
}

This function set a timer that every 1000 milliseconds (1 second) show you a new number so as to allow time for the child to count.

Look this example: https://jsfiddle.net/Frogmouth/bke47w3u/2/

if(myCount == 10) clearTimeout(_timeout) stop the timer when myCount is 10.

Add Cell to a table:

If you need to add the number like cell of table simply change the html container #main:

<table id="main"></table>

and the html printed by .innerHTML:

document.getElementById('main').innerHTML += "<tr><td>" + myCount + "</td></tr>";

This show you a table with 1 cell for each rows for a total of 10 rows.

Example: https://jsfiddle.net/Frogmouth/bke47w3u/5/

Upvotes: 1

Lal
Lal

Reputation: 14820

See this fiddle

You have to append the innerHTML each time you are performing the count. So you have to set the innerHTML as below

document.getElementById('main').innerHTML += countTotal + "<br />";

Upvotes: 0

Related Questions