View Full Version : Is there a better way than "getElementById" and a for loop to retrieve data?

02-06-2008, 12:39 AM
Hi everyone,
I have been working on a script that dynamically generates a pair of textboxes then assigns the user's input from each text box "a" into array "a" and the inputs from each text box "b" into array "b".

With my limited knowledge of javascript, I used div tags to help create the pairs of text boxes when the user clicks on "add pair" and I named each text box in the form a[ i ] and b[ i ], where i is intially zero and increases by one each time a pair of textboxes is added.

But whenever, I tried to obtain the value of, say, b[2] there was an error that said b[2] was null or not an object. It didn't look like arrays "a" and "b" were being formed. In fact, the only way I managed to retrieve the values from the text boxes was using "getElementById" and resorting to a for loop in order to make the arrays. I've never used "getElementById" before but that method only appears to be able to get elements from one pair of text boxes.

I have added a sample of the code below if anyone wants to take a look at it, I would appreciate any advice.


P.S. The function test() is just supposed to assign the input into the two arrays using the for loop I mentioned and show you the various index and array values as it assigns them. The plus sign is just supposed to act as a separator. If it did work and you were to add 3 pair of text boxes and not change the preset values, the output should look like:

i=2 j=0 a=1 b=2 <--- It stops at this point for some reason
i=2 j=1 a=1,1 b=2,2
i=2 j=2 a=1,1,1 b=2,2,2

(You should note that i = [no. of pairs]-1, "j" is the increment in the for loop and a & b are the growng arrays.)

var a = [];
var b = [];
var i = 0;

//adds pair of text boxes a[i] and b[i] in the div tags called div
function addPair() {
var c=document.getElementById("div");
c.innerHTML+="+ <input type='text' value='1' size=1 name='a[" + i + "]' id='a[" + i + "]'>";
c.innerHTML+=" and <input type='text' value='2' size=1 name='b[" + i + "]' id='b[" + i + "]'> ";

//tries to make the arrays that i thought would have formed above
function test() {
for (j=0;j<=i;j++)
document.write("i=" + i + " j=" + j + " a=" + a + " b=" + b + "<br>")
// -->

<div id="div"></div><input type="button" value="Add pair" onclick="addPair()"/>
<INPUT TYPE="button" VALUE="Test" onClick="test()">

02-06-2008, 02:03 AM
Sorry, the for loop should go until the value of j is "j<=(i-1)" not "j<=i" but that would only affect the last iteration.