InnerHTML with Javascript Loop Function

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

. This works, but the problem is that when I click the "Submit" button, this result only shows the last value, like this "10 * 10 = 100", but I want to start the full cycle, which I define in the code from 1 to 10 Please solve this problem.

<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> 
+4
source share
2 answers

Your for loop overwrites innerHTML of demop every time it executes. Therefore, when your for loop reaches the last iteration a , it will be 10 and therefore you will only get the last value "10 * 10 = 100"

So you have to add the result every time you repeat the for loop, just do it like this

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

So, you will get your output on separate lines.

+5
source

When you call demop.innerHTML = something , you rewrite it every time. You must either:

  • Put the whole line in the temporary variable result , and then pass it innerHTML
  • Combine the different results by doing

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

+1
source

Source: https://habr.com/ru/post/1441080/


All Articles