It was solved, thanks

I need to create an array that will keep track of each input in the form. But I don’t know why it isn’t working

The Code that won’t work:

let tracking = [];
for(let i = 0; i < tracking.length; i++) {
    console.log(tracking, tracking.length);

For some reason the loop never starts, the code only works if I write it like this:

let tracking = [];
for(let i = 0; i < tracking.length; i++);
    console.log(tracking, tracking.length);

But that makes a separate array in the console.log every time. So it never actually continues the array and the length is always “1” and the tracking is only ever the last (input). The Array is never adding new elements when there’s a new input

I think it’s never started to loop the empty array, not sure where the code is wrong?

Basically, each input in the form should push that input as a new element in the array, but it doesn’t work.

I don’t see the difference between your two codes.

But i = 0 and tracking.length = 0, so yeah the loop will never run because i is not less than 0.

It seems like a loop is unnecessary for pushing inputs to an array, but without seeing more code it’s hard to tell what you are ultimately trying to do.

Hello Sconim.

Here is what the two pieces of code do :

Code that won’t work :
i is 0 initially, and tracking.length is also 0. Before starting, we check if i<tracking.length , or 0<0. Since this is false, the loop never starts.

The second code :

  1. Set tracking to []
  2. Set i to 0. Now, if i < tracking.length, then keep increasing i. (At the end of this step, i will still be 0, because i<tracking.length is same as 0 < 0 initially, and the loop never starts).
  3. Now, add input to tracking. (tracking now becomes [input]).
  4. Display tracking, and tracking.length

What you want to do is, add every input to the array.

You can do it in the following manner :

var inputs = document.querySelector('#myform input');
// inputs is not an array
// but it has array-like .length property, and
// its values can also be accessed using an index
var aggr = [];
for(var i=0;i<inputs.length;i++){

Or if you’re using ES6, you get Array.from(), so you can use

let aggr = Array.from(document.querySelector('#myform input'));
// take an Array-like thing and convert it into an Array

Please do not change the message body after you got an answer, your question can be useful for other people searching the forum, and now they can’t know what you asked

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.