<p id="g"></p>
function input(){
var name = window.prompt("What's your name?")
var num = window.prompt("Input a number")
for (let i=0; i < num; i ) {
document.getElementById("g").innerHTML = "Hi, " name "!<br>";
}
}
why does it print only One (Hi, Name !br) in the page it should be how many times the user input in var num= prompt. .
and if I try Document.write in the function it writes it in another page how I resolve this ?
CodePudding user response:
Because document.getElementById("g").innerHTML = "Hi, " name "!<br>"
; will make the latter one override the previous data
In order to output as you expected,you need to store the content into a variable and assign it the element when the loop finished
function input(){
var name = window.prompt("What's your name?")
var num = window.prompt("Input a number")
let content = ""
for (let i=0; i < num; i ) {
content = "Hi, " name "!<br>";
}
document.getElementById("g").innerHTML = content;
}
CodePudding user response:
It is only printing one because each time the loop continues , innerhtml
overrides the previous one.
To solve this problem, change your code
From this:
<p id="g"></p>
function input(){
var name = window.prompt("What's your name?")
var num = window.prompt("Input a number")
for (let i=0; i < num; i ) {
document.getElementById("g").innerHTML = "Hi, " name "!<br>";
}
}
To this:
<p id="g"></p>
function input(){
var name = window.prompt("What's your name?")
var num = window.prompt("Input a number")
for (let i=0; i < num; i ) {
document.getElementById("g").innerHTML = "Hi, " name "!<br>";
}
}
check the snippet for better understanding:
function input() {
var name = window.prompt("What's your name?")
var num = window.prompt("Input a number")
for (let i = 0; i < num; i ) {
document.getElementById("g").innerHTML = "Hi, " name "!<br>";
}
}
input();
<p id="g"></p>