Nicholas Dry
Nicholas Dry

Reputation: 117

.innerHTML Not Displaying While Using a For Loop

I am attempting to write a script that will allow users to input numbers into a screen, add them to an array and then print the values on an innerHTML element.

However, when I attempt to use it in a for loop, nothing is printing out and it goes to a new page where the only thing displayed is the first number entered.

I am new at JavaScript and might be doing it incorrectly. Please let me know!

Thanks in advance

var a = [];

var count = 0;

function addNum() {
  a[count] = document.getElementById('input').value;
  count++;
}

function printValues() {
  for (i = 0; i < a.length; i++) {
    document.write(a[i], " ").innerHTML = array;
  }
}
<input type="text" id="input">
<br>
<input type="button" onclick="addNum();" value="Add Number">
<br>
<input type="button" onclick="printValues();" value="Print Numbers">
<p>
  <a id="array"></a>
</p>

Upvotes: 1

Views: 320

Answers (5)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

  • You typically would not use a "count" variable to add items to an array but would instead push to the array however I kept it in case you needed it otherwise.
  • You would as others noted not do a document.write to an element but instead use the innerHTML and replace or append to that.
  • Odd also that you are putting the innerHTML in a link <a /> element but since that is what you are using I will reproduce that.
  • IF you do want to use these as number (integers?) you would want to parse them with parseInt(string, radix); or parsefloat.
  • You did not have i set as a variable object so I did that here

Slightly reworked code here:

var a = [];

var count = 0;

function addNum() {
    a.push(parseInt(document.getElementById('input').value, 10));
    count++;
}

function printValues() {
    var i;
    var myValues = "";
    for (i = 0; i < a.length; i++) {
        myValues = myValues + a[i] + " ";
    }
    var element = document.getElementById("array");
    element.innerHTML = myValues;
}

Here is the code reproduced as a working example: http://jsfiddle.net/coffw8tg/

Upvotes: 0

srinivasan rb
srinivasan rb

Reputation: 11

The statement "document.write(a[i], " ").innerHTML = array;" is wrong. There is no variable named array declared in the code.

The correct form to print all the numbers using document.write is,

for (i=0;i<a.length;i++) {
     document.write(a[i] + " ");
}

If you need sum of all input numbers and the print the sum, then you can simply sum it up in a variable as you click addNumber button as,

var total = 0;
function addNum() {
    total += Number(document.getElementById('input').value);
}

function printValues() {
    document.write(total);
}

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

From MDN:

Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.

So your problem is caused by document.write. Once you write to your already loaded document, everything else is thrown away, including your javascript. (You had other problems too with just how you were using it, but this is the main problem).

You have an element with the id array, which I assume is where you want to put your numbers. So you need to get that element with getElementById and then set its innerHTML. You can use array.join to avoid the loop.

var a = [];

var count = 0;

function addNum() {
  a[count] = document.getElementById('input').value;
  count++;
}

function printValues() {
  document.getElementById('array').innerHTML = a.join(",");
}
<input type="text" id="input">
<br>
<input type="button" onclick="addNum();" value="Add Number">
<br>
<input type="button" onclick="printValues();" value="Print Numbers">
<p>
  <a id="array"></a>
</p>

A couple of other things you should look at. After adding a number in addNum, you should probably clear the text box by setting the value to null. Secondly, it's preferred to add event handlers in code rather than in your HTML.

Upvotes: 2

The Dark Knight
The Dark Knight

Reputation: 5585

What you are doing is not the correct way of setting stuff up in innerHTML . Also, you are not retaining the values to be printed on to the screen. Everytime , you click on print the new value inputted by the user is just getting passed and the old value is getting replaced with the new one . Here the variable valueToBePrinted will always remember the last value that was inputted as it concatenates all the inputted values to it, once the user is done with his/her input .

Look at the following piece of code :

var a = [];
var count = 0;

function addNum() {

    a[count] = document.getElementById('input').value;
    console.log(a[count]);
    count++;
}

function printValues() {
    var valueToBePrinted='';
    for (i=0;i<a.length;i++) {
      valueToBePrinted += a[i] + ' ';
      console.log(valueToBePrinted)
      document.getElementById('array').innerHTML =valueToBePrinted;
    }
}

Also , look at the result in the Fiddle here : Fiddle

Upvotes: 0

Mehmood
Mehmood

Reputation: 931

function printValues() {
    var strValues='';  // Initialize a temporary variable 

    for (i = 0; i < a.length; i++) {
      strValues += a[i] + ' ';            
    }
    document.write(strValues); //Writting variable to document.
}

In the above example we have create a temporary variable and sets the default value to blank. Then in for loop we concatenate the array value to variable using += sign.

Upvotes: 0

Related Questions