Tutorials - DOM Table Add Row

Add and delete rows dynamically in an HTML table

Add rows with an input and select, and validate, and add events.

Overview

What you'll find on this page is one technique of adding rows to a table - using W3C DOM table methods to add rows and cells, then using W3C DOM methods to create elements within those cells and to set their properties and events.

Before trying out this example, you may want to read my comparison of innerHTML vs. DOM vs. cloneNode

Try It

Validate Submit

Display OnKeyPress

Sample table
1

Explanation

A row is inserted at the end of the table using the insertRow method, and two cells are added. One cell has just text, and the other cell has an HTML input. There is more than one way to accomplish this. The technique here uses document.createTextNode and document.createElement to create the text and HTML input, respectively.

If you enter text into the text boxes, they are not affected when new rows are added. Each row gets a unique name, so if the values are being submitted to a server-side page, it can look for txtRow1, txtRow2, etc.

The Remove button deletes the last row using table method deleteRow. The JavaScript does a check to prevent the header or first row from being deleted.

Note: The "Submit" button is not necessary to add a row. I've included it to demonstrate how the values can be submitted. In this case, I'm not submitting it to a server-side page, but just to an HTML page, tableaddrow_nw.html, which opens in a new window. There is additional JavaScript in that page that I have not listed here. Feel free to view the source of that page.

2005-03-08 - Validation

By assigning an id to the new inputs, they can be referenced for validation. When the "Validate" check box is checked and "Submit" is clicked, the example does some simple validation by looping each input and checking for empty values. If any one of the inputs is empty, an alert displays the number of the first empty row, and the form is not submitted.

2005-05-26 - Adding events

The example now includes function keyPressTest, which is called for each of the text inputs. Add events to newly created objects by using the traditional event registration model.

Extra help: validate.html - Includes more information about keypress validation.

2005-10-25 - Select (drop down boxes)

There is now a cell with a select box. Refer to function addRowToTable.

Extra help: tutorial005.html - Includes more information about adding options to a select box.

2005-02-21 - setAttribute

In function addRowToTable, instead of using setAttribute, I changed it to use direct property references. Although setAttribute can be useful sometimes, this example doesn't require it.

For anyone who prefers to use setAttribute, here are the lines of code as I had them in the 2005-10-25 version:

	el.setAttribute('type', 'text');
	el.setAttribute('name', 'txtRow' + iteration);
	el.setAttribute('id', 'txtRow' + iteration);
	el.setAttribute('size', '40');
and
	sel.setAttribute('name', 'selRow' + iteration);

Browser Support

2006-02-21 - HTML Table Add Row has been tested and works in Firefox 1.5.0.1, Opera 8.02, Netscape 6.1, and Internet Explorer 6.0.

The example will not work in Netscape 4 and below or IE 5 and below.

Source

Public Domain

The HTML and JavaScript listed below are released to the public domain. Read the Terms of Use for details. The contents of this page are still copyrighted.

The JavaScript

// Last updated 2006-02-21
function addRowToTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);
  
  // left cell
  var cellLeft = row.insertCell(0);
  var textNode = document.createTextNode(iteration);
  cellLeft.appendChild(textNode);
  
  // right cell
  var cellRight = row.insertCell(1);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'txtRow' + iteration;
  el.id = 'txtRow' + iteration;
  el.size = 40;
  
  el.onkeypress = keyPressTest;
  cellRight.appendChild(el);
  
  // select cell
  var cellRightSel = row.insertCell(2);
  var sel = document.createElement('select');
  sel.name = 'selRow' + iteration;
  sel.options[0] = new Option('text zero', 'value0');
  sel.options[1] = new Option('text one', 'value1');
  cellRightSel.appendChild(sel);
}
function keyPressTest(e, obj)
{
  var validateChkb = document.getElementById('chkValidateOnKeyPress');
  if (validateChkb.checked) {
    var displayObj = document.getElementById('spanOutput');
    var key;
    if(window.event) {
      key = window.event.keyCode; 
    }
    else if(e.which) {
      key = e.which;
    }
    var objId;
    if (obj != null) {
      objId = obj.id;
    } else {
      objId = this.id;
    }
    displayObj.innerHTML = objId + ' : ' + String.fromCharCode(key);
  }
}
function removeRowFromTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function openInNewWindow(frm)
{
  // open a blank window
  var aWindow = window.open('', 'TableAddRowNewWindow',
   'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
   
  // set the target to the blank window
  frm.target = 'TableAddRowNewWindow';
  
  // submit
  frm.submit();
}
function validateRow(frm)
{
  var chkb = document.getElementById('chkValidate');
  if (chkb.checked) {
    var tbl = document.getElementById('tblSample');
    var lastRow = tbl.rows.length - 1;
    var i;
    for (i=1; i<=lastRow; i++) {
      var aRow = document.getElementById('txtRow' + i);
      if (aRow.value.length <= 0) {
        alert('Row ' + i + ' is empty');
        return;
      }
    }
  }
  openInNewWindow(frm);
}

The HTML

<form action="tableaddrow_nw.html" method="get">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
<input type="button" value="Submit" onclick="validateRow(this.form);" />
<input type="checkbox" id="chkValidate" /> Validate Submit
</p>
<p>
<input type="checkbox" id="chkValidateOnKeyPress" checked="checked" /> Display OnKeyPress
<span id="spanOutput" style="border: 1px solid #000; padding: 3px;"> </span>
</p>
<table border="1" id="tblSample">
  <tr>
    <th colspan="3">Sample table</th>
  </tr>
  <tr>
    <td>1</td>
    <td><input type="text" name="txtRow1"
     id="txtRow1" size="40" onkeypress="keyPressTest(event, this);" /></td>
    <td>
    <select name="selRow0">
    <option value="value0">text zero</option>
    <option value="value1">text one</option>
    </select>
    </td>
  </tr>
</table>
</form>

Supplemental Information

Related mredkj.com Tutorials

  1. DOM table methods
  2. DOM - Refer to table cells
  3. innerHTML vs. DOM vs. cloneNode
  4. Add rows with fade in
  5. Add rows, and submit to PHP
  6. DOM Table Add Row
  7. DOM Table Delete Row
  8. DOM Table Delete Row - includes a calendar

For starters, I'd recommend [3], and if you've decided to use a DOM approach, then check out the simple examples of [1] and [2]. Then you could move on the extended add/delete examples [6] and [7]. If you're looking for some specific functionality also check out [4], [5], and [8]

About this page: