Table Basics - DOM - Refer to table cells
Get the values from a table with text boxes and select boxes.
The example below starts off with a header row, and one row of data. If you click "Get Cells From The Last Row", it will get the values from each of the cells in the data row. If you then click "Append", a new row is dynamically added. Click "Get Cells From The Last Row" again, and the new row's values are retrieved.
Tested in the Windows versions of Firefox 1.0.7, IE 6.0, and Opera 8.02.
To get to a certain cell in a table, first a row is referenced using the DOM rows collection, then a cell is referenced using the DOM cells collection. To reference the contents of a cell, it will depend on what's in the cell. Cell 0 in the example contains a text node with no surrounding tags, so the text can be referenced with innerHTML. Cell 1 contains an input text element, and it is the firstChild in the cell, so that's how it's referenced. Cell 2 contains a select list, and is the firstChild for its cell.
HTML and the DOM
Various browsers handle the DOM in different ways, and in my example this affects the first (preexisting) row's table cells. While traversing the DOM, a browser such as Firefox 1.0.x will count whitespace as a text node, but Internet Explorer 6.0 won't count it as a node. On the other hand, a row that is added dynamically as is done in my function appendRow, will not include a text node in either browser.
If you want to test how your browser counts table cell whitespace, then refer to my DOM traverse script.
In the source of this page, refer to
<td>1</td> <td><input type="text" id="txtRow1" size="40" value="t1" /></td> <td><select> <option value="value0">option zero</option> <option value="value1">option one</option> </select></td>
And in tablebasics2.js, in the getCells function, refer to the following line:
outTxt1.value = tbl.rows[lastRow].cells.firstChild.value;
You'll notice that firstChild is used to get the first node in that cell. A DOM node call such as that would have been affected by the whitespace node.
Related mredkj.com Tutorials
- DOM table methods
- DOM - Refer to table cells
- innerHTML vs. DOM vs. cloneNode
- DOM Table Add Row
- DOM Table Delete Row
- DOM Table Delete Row - includes a calendar