Sergey Ivanov
Sergey Ivanov

Reputation: 3929

Get value from input in a table

I have the following code:

function create_row() {
    var table = document.getElementById("main_table");
    var n = table.rows.length;
    var m = table.rows[0].cells.length;
    var row = table.insertRow(-1);
    var cell = row.insertCell(0);
    cell.innerHTML = n;
    var cell = row.insertCell(1);
    cell.innerHTML = "<input size=10>";
    for (i=2; i<m; i++) {
        var cell = row.insertCell(i);
        cell.innerHTML = "<input size=4>";
    } 
}

function print_values() {
    var table = document.getElementById("main_table");
    for (i=1; i<table.rows.length; i++) {
        console.log(table.rows[i].cells[1].innerHTML);
    }
}

However, when I print values I get <input size="10">.

The problem is that when I create a row, I add manually some value to a table (in a webpage) and I want to print those values in a log. How can I access those values, but not html of the input?

I probably can assign an id to each input form and then access value keyword, but thought maybe it could suffice using table cells.

Upvotes: 0

Views: 68

Answers (2)

Kevin Grabher
Kevin Grabher

Reputation: 399

You want the insides of your input, so you'll have to select that input.

yourExistingSelector.querySelector("input").innerHTML

In your case:

table.rows[i].cells[1].querySelector("input").innerHTML

Upvotes: 0

Barmar
Barmar

Reputation: 780724

The input element is a child of the table cell. And you have to use .value to get the value of an input, not .innerHTML.

console.log(table.rows[i].cells[1].childNodes[0].value)

Upvotes: 2

Related Questions