innerHTML with For Loop in Javascript
Asked Answered
W

2

5

this is my coding. in this coding i want to print table in innerHTML in

paragraph tag.This is working but the problem is when i click submit button this result show only last value like this "10*10=100" but i want to run full loop which i define in code from 1 till 10. Please solve this issue.

<html>
<head>
<title>Table Program</title>
</head>
<body>
<input type="text" id="table" placeholder="Enter table"/>
<input type="button" value="Submit" onClick="table()"/>
<p id="demo"></p>
<!----------------------------------------------------------------------------------------------->
<script type="text/javascript">
function table()
{
    var value = document.getElementById("table").value;
    var demop = document.getElementById("demo");
    var a;
    for(a=1; a <= 10;++a)
    {
        demop.innerHTML=(value+"*"+ a +"="+ value*a);
    }
    }
</script>
</body>
</html>
Wichman answered 21/10, 2012 at 9:49 Comment(0)
M
13

Your for loop is overwriting the innerHTML of demop each time it is executing. So when your for loop reaches last iteration a will be 10 and hence you only get the last value "10*10=100"

So you should append the result every time you iterate your for loop just make it like this

demop.innerHTML += (value + "*" + a + "=" + (value*a) + "<br />");

So you will get your output on seperate lines.

Mesothorium answered 21/10, 2012 at 10:6 Comment(4)
Thanks for helping.Sir you are asolutely right.i have did this but now my another question is i want to clear table on requesting new table please tell me what should i do??Wichman
For your second question do one thing, before your for loop write this code demop.innerHTML = "" so it will clear all contents in your <p> tagMesothorium
can you please tell me which website or which company tutorial is best (All programming tutorials).Wichman
I have gone through many websites but none of them is a ONE STOP FOR ALL TUTORIALS. You should look at many websites for your need as each of them has something special to understand rather then relying on a single website.Mesothorium
C
1

When you call demop.innerHTML = something you overwrite it each time. You should either:

  • Put the entire string in a temporary result variable and then give it to innerHTML
  • Concatenate the different results by doing

    demop.innerHTML = demop.innerHTML + (value+"*"+ a +"="+ value*a);

Caracul answered 21/10, 2012 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.