0

I have to save temporary data for my webpage using java script.This is the way that i save i one by one since the data is an array.

var product= new Array();
product[1] = document.getElementById("product[1]").value;
product[2] = document.getElementById("product[2]").value;

This method is working. but when i run it by looping, it doesnt work.

for(var i=1; i < no_item; i++){
product[i] = document.getElementById("product[i]").value;
}

*product[] is a varibale that I take from a html dropdown menu

Can anyone please tell me the problem ? thanks ~ =)

Billy
  • 67
  • 1
  • 7

1 Answers1

1

Should be written as, as you are going to be getting the id "product[i]" every time with your original code. This will get "product[1]" then "product[2]" and so on:

for(var i=1; i < no_item; i++){
    product.push(document.getElementById("product[" + i + "]").value);
}

Also, as a comment, we tend to prefer var product = []; over var product = new Array(); in javascript but both will work.

megawac
  • 10,953
  • 5
  • 40
  • 61
  • thanks, it works.but abit weird.how can i start the array number with 1 and not with 0 ? another problem is when I use it with php, such as product[1] and product[2]. the value of product[1] is assign to product[2] and product[1] is empty. what is the problem ? – Billy Nov 12 '13 at 02:32
  • Is there a good reason to start with 1? You may want to read http://stackoverflow.com/questions/7320686/why-does-the-indexing-start-with-zero-in-c?lq=1 – megawac Nov 12 '13 at 02:36
  • @user2892997 You can do what you were doing `product[i] = ...` but it will exaggerate the length of the array as product[0] will be set to undefined – megawac Nov 12 '13 at 02:37
  • $product=@$_GET['product']; This is the code for php that i collect the array and use, but the array is not in order to what I want.The value of product[1] is assign to product[2] and product[1] is empty. Can you please guide me on this? – Billy Nov 12 '13 at 02:40
  • lets say i key in 1,2,3 as the first three array, when i read the , the array is like this , array1 =1 array2 = , array3 =2 array4 = , array5=3 , the comma is included in the array. how can i solve this ? – Billy Nov 12 '13 at 02:47
  • All indexs will be i-1 in an array. You really should not be accessing the values explicitly by index and if you need to store some data about some item in an array I would wrap it in an object - eg: `product.push({id:i, value: document.getElementById("product[" + i + "]").value}) – megawac Nov 12 '13 at 02:48
  • List (arrays in js are lists) indexs should really not be used for state stuff in (any) language – megawac Nov 12 '13 at 02:49