0

I have a HTML like this:

<table id="laboral">
    <tr>
        <td><input type="text" name="start"/></td>
        <td><input type="text" name="end"/></td>
        <td><textarea name="desc"></textarea></td>
        <td><button type="button" onclick="saveValues(this);createRow('laboral')"> + </button></td>
    </tr>
</table>

What I want is to save the values in the three cells (2 inputs and 1 textarea).

The button creates another row just like the first, with the same inputs and names. The problem is that I don't know how to access THIS row, I mean, the row who owns the button.

I tried with this.parentNode.parentNode but didn't work.

4

2 回答 2

1

尝试这个

<table id="laboral">
    <tr>
        <td><input type="text" name="start"/></td>
        <td><input type="text" name="end"/></td>
        <td><textarea name="desc"></textarea></td>
        <td><button type="button" onclick="saveValues(this)"> + </button></td>
    </tr>
</table>

 

var inputVals = [];

function saveValues(elm) {
    //         button   td         tr        tbody     table
    var table = elm.parentNode.parentNode.parentNode.parentNode;

    //  iterating through the first row cells
    for (var i = 0; i<table.rows[0].cells.length-1; i++) {
        //  the current cell
        var cell = table.rows[0].cells[i];
        //  pushing the input elm's value into the array
        inputVals.push(cell.childNodes[0].value);
        //  retrieving the pushed value
        alert(inputVals[i]);
    }
}

小提琴示例

您可以修改代码。

于 2013-11-09T16:57:30.043 回答
1

您将对按钮的引用传递给saveValues,因此在saveValues第一个参数中将引用按钮。让我们称该参数btn. btn.parentNode将是td包含按钮,并且`btn.parentNode.parentNode将是tr包含 that td。所以:

function saveValues(btn) {
    var tr = btn.parentNode.parentNode;
    // Work with `childNodes` and the `childNodes` of those children to get the values
}
于 2013-11-09T16:28:58.330 回答