Fustigador
Fustigador

Reputation: 6469

Get the values from an array

I have a table in my jsp:

<table id="table">
    <tr>
        <th>Valor</th>
        <th>Recompensa</th>
    </tr>
    <tr>
        <td>
            <input type="text" name="amount">
        </td>
        <td>
            <input type="text" name="text">
        </td>

    </tr>

</table>

<input type="button" value="Send" onclick="send('table')"/>

I write something in the boxes, and press Send, and the send Javascript method is called.

Javascript send method, which iterates through rows and cells, and stores the values in an Array:

function send(tableID) {


        var table = document.getElementById(tableID);


        var array= new Array();

        for (var i = 1;i<table.rows.length; i++){

            var row = table.rows[i];
            for (var j = 0;row.cells.length; j++){

                alert("added to array: "+row.cells[j].innerHTML);
                array.push(row.cells[j].innerHTML);

            }
        }
    }

I am getting "<input name="amount" type="text">" in the alert. I have tried using row.cells[j].firstChild.innerHTML, receiving undefined.

What am I doing wrong? how could I get what the user writes in the textboxes?

PS: I'm using Firefox to test. Maybe a browser issue?

Upvotes: 1

Views: 70

Answers (3)

Gavin
Gavin

Reputation: 7954

You can use:

alert("added to array: " + row.cells[j].getElementsByTagName('INPUT')[0].value);

jsFiddle Example: http://jsfiddle.net/4TjYH/

EDIT: By the way, the code you posted may have been stripped down for simplicity, but if it's your actual code you can really simplify it:

function send(tableID) {
    var array = new Array(),
        inputs = document.getElementById(tableID).getElementsByTagName('INPUT');
    for (var i = 0; i < inputs.length; i++){
        alert("added to array: " + inputs[i].value);
        array.push(inputs[i].value);
    }
}

Upvotes: 3

TrazeK
TrazeK

Reputation: 838

Well, if you just want what the user has typed in the textboxes, you can assign ids to each textbox and use getElementById():

 <input type="text" name="amount" id="amount">
 <input type="text" name="text" id="text">

 var amount = document.getElementById("amount");
 var text = document.getElementById("text");

Then just push those two values on your array:

array.push(amount.value);
array.push(text.value);

You can put this logic in a loop, looping through an array of element ids or something if you didn't want to write similar code over and over.

Upvotes: 0

Mic
Mic

Reputation: 523

In the second loop is an error:

for (var j = 0; j < row.cells.length; j++){

"j <" was missing. the same problem was in the answer of Gavin: here the edit fiddle: http://jsfiddle.net/h693g/2/

Upvotes: 2

Related Questions