Javascript getting the value of an input in a tabl

2019-06-06 16:33发布

问题:

This question already has an answer here:

  • How to retrieve value of input type in a dynamic table 5 answers

I'm just wondering if it's possible to get the value of an html input in a table without naming each input separately and using getElementById directly onto the input so if I had the following table

<table id="table01">
<tr>
    <td>row 0 cell 0</td>
    <td>row 0 cell 1</td>
</tr>
<tr>
    <td>row 1 cell 0</td>
    <td>row 1 cell 1</td>
</tr>
</table>

I know in Javascript you can use the following to get the value of a specific cell in a specific row using the following

var lv_value = document.getElementById("table01").rows[0].cells[1].innerHTML;
console.log(lv_cont);

and this would give me the value I want which is "row 0 cell 1".

If I had a table like the following however

<table id="table01">
<tr>
    <td>row 0 cell 0</td>
    <td>row 0 cell 1</td>
    <td><input type="text" class="tbl_input"></input></td>
</tr>
<tr>
    <td>row 1 cell 0</td>
    <td>row 1 cell 1</td>
    <td><input type="text" class="tbl_input"></input></td>
</tr>
</table>

Is it then possible to do something along the lines of

<!-- this is obviously wrong -->
var lv_input = document.getElementById("table01").rows[0].cells[2].input.value;
console.log(lv_input);

to get the value of the input in the first row

回答1:

You should do something like this:

var lv_input = document.getElementById("table01").rows[0].cells[2].firstChild.value;
console.log(lv_input);

or use the querySelector to find the input element

var lv_input = document.getElementById("table01").rows[0].cells[2].querySelector('input').value;
console.log(lv_input);