Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 603
user2135738 Avatar asked May 24 '13 17:05

user2135738


1 Answers

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);

like image 132
user1106925 Avatar answered Sep 26 '22 00:09

user1106925