fekioh
fekioh

Reputation: 996

Get values from table of text fields javascript

I have a form which actually is a table of text fields. The html looks like this:

<form>
  <table id="table">
            <tr>
              <th>Player</th>
              <th>Number</th>
              <th>Con.per.day</th>
              <th>P.100.kg</th>
              <th>P.day</th>
              <th>I.month</th>
            </tr>

            <tr>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td>Result</td>
             </tr>


            <tr>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td>Result</td>
            </tr>


            <tr>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td><input type="text" /></td>
              <td>Result</td>
            </tr>

        </table>
        <input type="button" name="rank" value="Rank" onClick="rankPlayers(this.form)"/>
    </form>

I would like to iterate all fields and get the values at the press of the button, but I get undefined returned in the console log. I don't want to use IDs for each field as I want to do some column operations (add, multiply). My script for the first column looks like this:

            function rankPlayers(){
            var table=document.getElementById("table");
            for(var i=1; i<table.rows.length;i++){

                    console.log(table.rows[i].cells[0].value);
            }
        }

Any tips? Thanks

Upvotes: 5

Views: 20247

Answers (2)

tymeJV
tymeJV

Reputation: 104775

You can change your loop to:

    var table=document.getElementsByTagName("td");
    for(var i=1; i<table.length;i++){
        console.log(table[i].firstChild.value);
    }

This gets all td elements, loops them, and checks the firstChild value

Upvotes: 0

user1106925
user1106925

Reputation:

You need to select the input from the cell:

// ------------------------------------v
console.log(table.rows[i].cells[0].firstChild.value);

If you could have siblings (even whitespace) around the inputs, then you can use the .children collection to target the correct element.

// ------------------------------------v
console.log(table.rows[i].cells[0].children[0].value);

Upvotes: 12

Related Questions