Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2d array of form elements in js?

Status
Not open for further replies.

tyler2k

Programmer
Feb 3, 2011
2
0
0
ES
hi, my first post :)
hope somebody can help me. I have a html form with an 2d array of input fields. i need to be able to reference this array from js. i have seen a post that explains how to do it for a 1d array of inputs, but im not able to "replicate" it for a 2d array.

the html is this (sorry i dont know how to post this as "code"...)
Code:
<input type="text" name="par[0][name]" value=""/>
<input type="text" name="par[0][price]" onblur="process()" value=""/>
<input type="text" name="par[0][quantity]" onblur="process()" value=""/>


<input type="text" name="par[1][name]" value=""/>
<input type="text" name="par[1][price]" onblur="process()" value=""/>
<input type="text" name="par[1][quantity]" onblur="process()" value=""/>

<input type="text" name="par[2][name]" value=""/>
<input type="text" name="par[2][price]" onblur="process()" value=""/>
<input type="text" name="par[2][quantity]" onblur="process()" value=""/>

then in the js function i have tried to retrieve it with:

Code:
var mult = document.mi_form.elements["par[][]"];

any help please?
 
Unfortunately unlike PHP, JS does not automatically translate element names into arrays. For JS your element names are not arrays but simply strings.

Doing this: document.mi_form.elements["par[][]"]; makes it look for an element whose literal name is par[][].

You are going to have to loop through your elements manually to create your functional array.
Something like this should work:

Code:
 var mult=new Array();
var elms=document.forms.formname.elements;

for(var i=0; i<=(elms.length/3)-1;i++){
mult[i]=new Array();

var subElm='par[' + i + ']';
mult[i]['name']=elms[subElm + '[name]'];
mult[i]['price']=elms[subElm + '[price]'];
mult[i]['quantity']=elms[subElm + '[quantity]'];
}






----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top