Using a for loop and document.getElementById to populate an array in Javascript

25,622

Solution 1

What is the problem? You never mention what kind of results being generated or what the front-end html code looks like.

The js looks compilable, but here are some pointers.

The number 0 is before 1

It's a good habit to get in this mind set, plus it might save you from making stupid mistakes later on. Anyway, just to reinforce this, below is a number chart.

    0      10
    1      11
    2      12
    3      13
    4      14
    5      15
    6      16
    7      17
    8      18
    9      19

Avoid unnecessary variables

Having a js compiler that optimizes redundant code is sadly new feature. But still, why have two lines to maintain when you can have one.

var nums = [];

for( var i = 0; i < 18; i++ ) {
    nums[i] = parseInt( document.getElementById("spin" + i).value );
}

Don't push, insert

The push method has an expensive overhead so use it with caution.

Loggers

The console has a built in logger, why not use that instead of an alert box?

console.log( nums.length );

Solution 2

try this

var nums = [];

for(var i = 1; i <= 18; i++){
    var num= parseInt(document.getElementById("spin" + i).value);

    nums.push(num);

}

alert(nums.length);

Solution 3

A couple of things to note:

  1. As PSR has mentioned, you use:
var num[i]

when it should be

var num
  1. getElementById(id).value only works for form elements, you have to use .innerHTML for divs.

This works for me: http://jsfiddle.net/sbqeT/

Share:
25,622
Paul
Author by

Paul

I have a passion for Linux and Web Development. I'm here to learn and help others!

Updated on March 20, 2020

Comments

  • Paul
    Paul about 4 years

    I have been trying to populate an array using a for loop and taking such values using document.getElementById("spin " + i).value;

    The ids on my html for every input tag go from spin1 to spin18.

    Any suggestions on what I am doing wrong? Or what I can change?

    var nums = [];
    
    for(var i = 1; i <= 18; i++){
        var num[i] = parseInt(document.getElementById("spin" + i).value);
    
        nums.push(num[i]);
    
    }
    
    alert(nums.length);