Audrey
Audrey

Reputation: 1

defining a variable to output innerHTML

I've included the HTML code to give the whole picture of what I am trying to understand.

<html>
<head>
<title>Echo App</title>

</head>
<body>
<p>Echo</p>
<p>Say what? <input id="sayThis" size="40" /></p>
<p>How many times? 
<select id="howMany">
<option value="1">1</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
</select></p>

<p><button onClick="doLoop()">Do it!</button></p>
<p><div id="results"></div></p>
<script type="text/javascript" language="javascript">

function doLoop() {

var sayWhat = document.getElementById("sayThis").value;
var maxLoop = document.getElementById("howMany").value;

var str = ""; // where we'll store our output temporarily
for (var i=1; (i<=maxLoop); i++) {
    str = str + i + ":" + " " + sayWhat + '<br>';

}

document.getElementById("results").innerHTML=str;
}
</script>
</body>
</html>

How would the code be written out for this use of 'str'

str = str + i + ":" + " " + sayWhat + '<br>';

And, more especially, how would the code be written out for this use of 'str'

document.getElementById("results").innerHTML=str;

I look forward to your replies/answers. Thank you.

Upvotes: 0

Views: 12069

Answers (2)

Naftali
Naftali

Reputation: 146302

your code works fine, look at it here :-)

http://jsfiddle.net/maniator/s8fyQ/

The reason why it works:
This is because str is first set as an empty string, ad as you go through the loop you add on more text.
document.getElementById("results").innerHTML=str; sets the html of the element with the id=results to whatever is inside of the str variable that you set earlier

UPDATE

Instead of using str you can do:

   for (var i=1; (i<=maxLoop); i++) {
        document.getElementById("results").innerHTML = 
            document.getElementById("results").innerHTML + i
                + ":" + " " + sayWhat + '<br>';
    }

Upvotes: 3

Mike Thomsen
Mike Thomsen

Reputation: 37506

If you're trying to understand why it works, it's simple.

Your code creates a new variable, adds new text to that variable in each iteration of the loop and then sets the value of innerHTML. When you set the value of innerHTML, the browser triggers a behavior which causes it to dynamically update the tag you told it (results).

Upvotes: 0

Related Questions