Introduction
This article shows you how to add rows to an HTML table dynamically, using DHTML and JavaScript - without requiring a round trip to the web server. I used this technique
in a project to build a data entry grid, where the users wanted the flexibility to add or remove rows easily before doing a final submit/save.
The Code
The code has been tested to work with Internet Explorer 5 and above. It may work with other browsers, but I have not tested this.
The sample code has two JavaScript functions - one to add new rows and the other to delete rows. I have kept the page deliberately simple and removed all style
and formatting so that the readers are not bogged down with unnecessary information. The functions are simple and self-explanatory.
function addRow()
{
var newRow = document.all("tblGrid").insertRow();
var oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t1'>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t2'>";
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' name='t3'> <input" +
" type='button' value='Delete' onclick='removeRow(this);'/>";
}
function removeRow(src)
{
var oRow = src.parentElement.parentElement;
document.all("tblGrid").deleteRow(oRow.rowIndex);
}
Usage
To use the functions, you need to create an HTML table and give it a unique ID. The sample code uses tblGrid
as the ID, but you can use any other name - just make
sure to modify the function to use the new name. Next, you would need to modify the addRow
function to ensure that the correct number of cells are added and their
innerHTML
is set properly.
You can try out a working sample of the code at: http://www.interviewboard.com/DHTMLSamples/DHTMLGridSample.htm.
Conclusion
This is a simple and effective solution for creating data entry grids where the number of rows to be entered is indeterminate. It relies solely on the client side programming model,
thus avoiding server round trips while adding rows. You are not restricted to using simple text boxes for the grid - by changing the innerHTML
property of the cells
in the addRow
function, you can include drop-downs and radio buttons as well.
In a future article, I will show you how to extend the functionality of this grid to include keyboard support and posting the selected text boxes programmatically.