viktor
viktor

Reputation: 1048

read an array dynamically using getElementById

I am trying to read values from a form dynamically created by user and insert them in an 2 dimensional array. The ID of any field is created dynamically and it has the value 11, 12, 13 etc, depending on the rows and cols of the table. I try to read it using getElementByID but it seems to not work. The function is as follows:

            function readMatrix () {
        for (i = 0; i < k; i++) {
            for (j = 0; j < k; j++)
            A[i][j]=parseFloat(getElementById(ij).value, 10);
        }
    }

Upvotes: 0

Views: 213

Answers (3)

VisioN
VisioN

Reputation: 145388

You have a problem with getElementById call and argument. Try this:

function readMatrix() {
    for (var i = 0; i < k; i++) {
        for (var j = 0; j < k; j++) {
            var id = "" + (i + 1) + (j + 1);
            A[i][j] = parseFloat(document.getElementById(id).value);
        }
    }
}​

Pay attention you have IDs starting from 11 but not 00, so (i + 1) + (j + 1) part is added.

DEMO: http://jsfiddle.net/VnvM2/

Upvotes: 1

Jashwant
Jashwant

Reputation: 28995

I guess, elements id is concantenation of i and j , rather than addition.

So, it should work,

   function readMatrix () {
        for (i = 0; i < k; i++) {
            for (j = 0; j < k; j++)
            A[i][j]=parseFloat(document.getElementById(i + '' + j).value, 10);
        }
    }

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

First, it's document.getElementById(...) - that part is important, otherwise it can't find the getElementById function.

Next, you're having it look for a variable called ij, which is not what you want. You want the two numbers concatenated, so that can either be i*10+j or ""+i+j, whichever you prefer.

Upvotes: 2

Related Questions