NewbietoJedi
NewbietoJedi

Reputation: 1

Javascript Array not being filled

So i'm trying to self learn HTML and Jscript but i cannot figure out for the life of me what i've did wrong in this piece of code, its a drop down question list that asks the user what fruits they like, and their asking to make 9 answers, so this script is to capture those answers and store them in an array but when it breaks outside the loop the last alert does not show, so i can see the array is not actually getting filled.

I used the alerts for bug checking :)

 <script>
      function submitInfo(passed){
           var Fruit = [];
           var myForm = passed+"Form";

           //alert("here start"+" "+document.getElementById(myForm).length+" "+myForm);
           for (var i = 0; i < document.getElementById(myForm).length; i++) {
                //alert("in loop");
                var myFruit = passed+"Input"+i;
                //alert(myFruit+" "+document.getElementById(myFruit).value);

                Fruit.push(document.getElementById(myFruit).value);
                // var Fruit[i] = document.getElementById(myFruit).value;
                alert(Fruit[i]);
           }
           alert(Fruit[i]);
      }
 </script>

Thank you in advance for any help, it is appreciaed

Upvotes: 0

Views: 172

Answers (1)

musefan
musefan

Reputation: 48415

The array is being populated correctly, it's just that you are not testing it correctly.

The reason is because after your loop, i will be equal to document.getElementById(myForm).length. So when you use it to access the Fruit array you are accessing an index which has not been populated. You can prove this by doing the following after the loop:

alert(i);

For example, if document.getElementById(myForm).length is say 5. Your loop will run for 0..4 but it will still increment to 5 prior to deciding to break the loop (it has to increment it so it can evaluate the condition). At this point you will have 5 items in your array (indices 0-4). Then when you call the last alert, i = 5, but Fruit[5] does not exist.

If you were to change the last alert (after the loop) to Fruit[0] it should display the first item. You could also do console.log(Fruit) and check the console for the full contents of the array.

This may help to demonstrate it better.

Upvotes: 2

Related Questions