Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think you are clearing your array of names every time you call the function. You should bring the line:</p> <pre><code>nameArray = []; </code></pre> <p>out and make it global.</p> <p>I ran a quick test and the following code works in at least FireFox</p> <p><strong>Edited to use appendChild</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type='text/javascript'&gt; var names = []; function addName() { var nameTxt = document.getElementById('name_txt'); var name = nameTxt.value; names.push(name); var outTable = document.getElementById('out_tbl'); var row = document.createElement('tr'); var entry = document.createElement('td'); var txt = document.createTextNode(name); entry.appendChild(txt); row.appendChild(entry); outTable.appendChild(row); var numDiv = document.getElementById('num_div'); removeAllChildren(numDiv); var numTxt = document.createTextNode('You have ' + names.length + ' names'); numDiv.appendChild(numTxt); } function removeAllChildren(e) { while (e.hasChildNodes()) { e.removeChild(e.firstChild); } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table id='out_tbl'&gt; &lt;/table&gt; &lt;div id='num_div'&gt;You have 0 names&lt;/div&gt; &lt;input id='name_txt' type='text'/&gt; &lt;button onclick="addName()"&gt;CLICK&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Edit:</strong> Oh yeah and you are the fact that you are looping through the array every time. If you "globalize" the name array, you're gonna print the whole array every time you add a name.</p> <p><strong>Edit x2:</strong> the code you originally posted had nameArray as a local variable inside the function. This effectively clears the array every time you call the function. Then every time you call the function you add the current name to the now empty array, and loop through all 1 (one) elements that the array now holds.</p> <p>What you want to do is "globalize" the name array, and remove the loop from your function. This will allow you to build up your name array across multiple calls, and works the way that you want it.</p> <p>Also, innerHTML is not really the best way to add things to the page. I would suggest using appendChild().</p> <p>-C </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload