Friday, March 21, 2014

How to Change HTML Table Cell Value

First, we need to get a reference to a table cell value.

var table = document.getElementById('myTableId');

An HTMLTableElement has a rows property that refers to the table rows collection. An HTMLTableRowElement has a cells property that refers to the row cells collection.

With this information at hand it is easy to get a reference to any cell.

Let's say, we need to refer to the first column of the first row.

Since the collection index starts at 0 we can get this reference using the following code:

var cell = table.rows[0].cells[0];

The cell variable now refers to the cell in the first column and first row.
The data in the table cell is represented by a text node. We can get a reference to it by using the firstChild property of an HTMLElement.

We obtain a reference to the text node value by using its data property.

var value = cell.firstChild.data;

Now it is easy to change the text in a table cell:

cell.firstChild.data = 'my new text';

What if you have an HTML object in your data cell, like a radio button ? In this case, 'firstChild' property will refer to this object, and you can get all the properties of the object by referring to the cell's firstChild property, e.g:

cell.firstChild.value
cell.firstChild.name
cell.firstChild.type
 

Change table cell value automatically


To change a table cell value automatically we must assign an event handler to the cell onblur event.

For DOM scripting, I would recommend an excellent book on the subject by Jeremy Keith DOM Scripting: Web Design with JavaScript and the Document Object Model. It will teach you to work with DOM and JavaScript from the ground up.

 Some other posts you might find interesting:

How to Hightlight Table Rows

Extract Table Text