Javascript getting the value of an input in a table

11,777

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);
Share:
11,777
TheLovelySausage
Author by

TheLovelySausage

Primarily Informix-4GL Programmer, Linux Bash Programmer and Linux Administrator. Dabbler in Java, Python, HTML, PHP and JavaScript. Expert at breaking everything.

Updated on June 15, 2022

Comments

  • TheLovelySausage
    TheLovelySausage almost 2 years

    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