0
    <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?

  • You might want to check out [JS enclosures](http://stackoverflow.com/questions/3273210/javascript-closures-variable-scope-question) – Terry Apr 23 '14 at 00:07

2 Answers2

2

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];
Dave Bush
  • 2,382
  • 15
  • 12
0

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>
Guffa
  • 687,336
  • 108
  • 737
  • 1,005