Reputation: 17
<div id="story"></div>
<script>
function go(){
var test = [];
for (i=1; i<11; i++){
test[i]=i;
var words = document.getElementById(test[i]).value
document.getElementById("story").innerHTML="hello "+test[i];
}
}
I want everything from the for loop to be written in the div. However, only the last value of the loop (10) is being written into the div. How can i get all of the values written in there?
Upvotes: 0
Views: 696
Reputation: 700262
All the values are written to the element, but each value overwrites the previous one.
Collect the values in an array, and write them all to the element after the loop. Example:
<div id="story"></div>
<script>
function go(){
var test = [];
var msg = [];
for (i=1; i<11; i++){
test[i]=i;
var words = document.getElementById(test[i]).value
msg.push("hello "+test[i]);
}
document.getElementById("story").innerHTML = msg.join(', ');
}
go();
</script>
Upvotes: 0
Reputation: 2402
you are replacing the innerHTML you want to concatenate use +=
document.getElementById("story").innerHTML+="hello "+test[i];
or
document.getElementById("story").innerHTML =
document.getElementById("story").innerHTML + "hello "+test[i];
Upvotes: 2