<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Tutorials - DOM Table Add Row - mredkj.com</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="tutorials, learn, javascript, java, visual basic" />
<meta name="description" content="Add and delete rows dynamically to an HTML table." />
<script type="text/javascript" src="../javascript/windowOpen.js"></script>
 

 
<script language="JavaScript" type="text/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);
}
//-->
</script>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> 
</script>
<script type="text/javascript"> 
_uacct = "UA-83058-1";
urchinTracker();
</script>
</head>
<body>
 
<div id="topbanner">
<div id="logo">
<a href="../index.html">&nbsp;</a>
</div>
<div id="search">
<!-- SiteSearch Google -->
<form method="get" action="http://www.google.com/custom" target="_top">
<input type="hidden" name="domains" value="mredkj.com"></input>
<input type="hidden" name="client" value="pub-3639465516195777"></input>
<input type="hidden" name="forid" value="1"></input>
<input type="hidden" name="ie" value="ISO-8859-1"></input>
<input type="hidden" name="oe" value="ISO-8859-1"></input>
<input type="hidden" name="cof" value="GALT:#993333;GL:1;DIV:#993333;VLC:993333;AH:center;BGC:FFFFFF;LBGC:000000;ALC:0000A0;LC:0000A0;T:000000;GFNT:C07000;GIMP:C07000;LH:50;LW:200;L:http://www.mredkj.com/images/mredkj_logo_block.gif;S:http://;FORID:1;"></input>
<input type="hidden" name="hl" value="en"></input>
<div id="googleLogo">
<a href="http://www.google.com/"><img src="http://www.google.com/logos/Logo_25blk.gif" border="0" alt="Google"></img></a>
</div>
<div id="googleTxtbox">
<input type="text" name="q" size="21" maxlength="255" value=""></input>
</div>
<div id="googleSearchBtn">
<input type="submit" name="sa" value="Search"></input>
</div>
<div id="googleOptions">
<input type="radio" name="sitesearch" value=""></input> Web <input type="radio" name="sitesearch" value="mredkj.com" checked="checked"></input> mredkj.com
</div>
</form>
<!-- SiteSearch Google -->
</div>
</div>
 
<div id="content">
	<div id="innercontent">
		<h1 id="title1">Tutorials - DOM Table Add Row</h1>
		<h2 id="title2">Add and delete rows dynamically in an HTML table</h2>
		<h2 id="title2b">Add rows with an input and select, and validate, and add events.</h2>
		<h2>Overview</h2>
<p>
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.
</p>
<p>
Before trying out this example, you may want to read my comparison of
<a href="tablebasics3.html">innerHTML vs. DOM vs. cloneNode</a>
</p>
 
<h2>Try It</h2>
<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  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>
 
<hr />
 
<h2>Explanation</h2>
<p>
A row is inserted at the end of the table using the <b>insertRow</b> 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 <b>document.createTextNode</b> and <b>document.createElement</b>
to create the text and HTML input, respectively.
</p>
 
<p>
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.
</p>
 
<p>
The Remove button deletes the last row using table method <b>deleteRow</b>.
The JavaScript does a check to prevent the header or first row from being deleted.
</p>
 
<p>
Note: The &quot;Submit&quot; 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.
</p>
 
<h3>2005-03-08 - Validation</h3>
<p>
By assigning an id to the new inputs, they can be referenced for validation.
When the &quot;Validate&quot; check box is checked and &quot;Submit&quot; 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.
</p>
 
<h3>2005-05-26 - Adding events</h3>
<p>
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.
</p>
<p>
Extra help: <a href="validate.html">validate.html</a> - Includes more information about keypress validation.
</p>
 
<h3>2005-10-25 - Select (drop down boxes)</h3>
<p>
There is now a cell with a select box.
Refer to function <strong>addRowToTable</strong>.
</p>
<p>
Extra help: <a href="tutorial005.html">tutorial005.html</a> - Includes more information about adding options to a select box.
</p>
 
<h3>2005-02-21 - setAttribute</h3>
<p>
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.
</p>
<p>
For anyone who prefers to use setAttribute, here are the lines of code as I had them in the 2005-10-25 version:
</p>
<pre class="codeblock">
	el.setAttribute('type', 'text');
	el.setAttribute('name', 'txtRow' + iteration);
	el.setAttribute('id', 'txtRow' + iteration);
	el.setAttribute('size', '40');
</pre>
and
<pre class="codeblock">
	sel.setAttribute('name', 'selRow' + iteration);
</pre>
 
<h2>Browser Support</h2>
 
<!--
2005-05-26 - HTML Table Add Row has been tested and works in Firefox 1.0.4, Mozilla 1.7.7, Opera 7.54, Netscape 6, and IE 6.0.
-->
 
<!--
2005-10-25 - HTML Table Add Row has been tested and works in Firefox 1.0.7, Opera 8.02, Netscape 6.1, and Internet Explorer 6.0.
-->
 
<p>
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.
</p>
 
<p>
The example will not work in Netscape 4 and below or IE 5 and below.
</p>
 
<a name="theSource"></a>
<h2>Source</h2>
 
<h3>Public Domain</h3>
<p>
<small>
The HTML and JavaScript listed below
are released to the public domain.
Read the <a href="../legal.html">Terms of Use</a> for details.
The contents of this page are still copyrighted.
</small>
</p>
 
<h3>The JavaScript</h3>
<div class="codeblock">
<pre>
// 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 &gt; 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&lt;=lastRow; i++) {
      var aRow = document.getElementById('txtRow' + i);
      if (aRow.value.length &lt;= 0) {
        alert('Row ' + i + ' is empty');
        return;
      }
    }
  }
  openInNewWindow(frm);
}
</pre>
</div>
 
<h3>The HTML</h3>
<div class="codeblock">
<pre>
&lt;form action=&quot;tableaddrow_nw.html&quot; method=&quot;get&quot;&gt;
&lt;p&gt;
&lt;input type=&quot;button&quot; value=&quot;Add&quot; onclick=&quot;addRowToTable();&quot; /&gt;
&lt;input type=&quot;button&quot; value=&quot;Remove&quot; onclick=&quot;removeRowFromTable();&quot; /&gt;
&lt;input type=&quot;button&quot; value=&quot;Submit&quot; onclick=&quot;validateRow(this.form);&quot; /&gt;
&lt;input type=&quot;checkbox&quot; id=&quot;chkValidate&quot; /&gt; Validate Submit
&lt;/p&gt;
&lt;p&gt;
&lt;input type=&quot;checkbox&quot; id=&quot;chkValidateOnKeyPress&quot; checked=&quot;checked&quot; /&gt; Display OnKeyPress
&lt;span id=&quot;spanOutput&quot; style=&quot;border: 1px solid #000; padding: 3px;&quot;&gt; &lt;/span&gt;
&lt;/p&gt;
&lt;table border=&quot;1&quot; id=&quot;tblSample&quot;&gt;
  &lt;tr&gt;
    &lt;th colspan=&quot;3&quot;&gt;Sample table&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;1&lt;/td&gt;
    &lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;txtRow1&quot;
     id=&quot;txtRow1&quot; size=&quot;40&quot; onkeypress=&quot;keyPressTest(event, this);&quot; /&gt;&lt;/td&gt;
    &lt;td&gt;
    &lt;select name=&quot;selRow0&quot;&gt;
    &lt;option value=&quot;value0&quot;&gt;text zero&lt;/option&gt;
    &lt;option value=&quot;value1&quot;&gt;text one&lt;/option&gt;
    &lt;/select&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
&lt;/form&gt;
</pre>
</div>
 
<hr />
 
<h2>Supplemental Information</h2>
<ul>
<li>
<a href="http://www.mozilla.org/docs/dom/domref/dom_html_ref31.html" target="_blank">insertRow()</a>
- Gecko DOM Reference
</li>
<li>
<a href="http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/insertrow.asp" target="_blank">insertRow Method</a>
- MSDN Reference
</li>
<li>
<a href="http://www.faqts.com/knowledge_base/view.phtml/aid/2179" target="_blank">How do I add a row to a table?</a>
- This page at FAQTs.com has two techniques of adding text to a table,
and also checks for browsers that support document.all (e.g. Internet Explorer 5). 
</li>
<li>
<a href="http://www.quirksmode.org/js/events_tradmod.html" target="_blank">Traditional event registration model</a>
- quirksmode.org
</li>
</ul>
 
<h2>Related mredkj.com Tutorials</h2>
<ol>
	<li><a href="tablebasics1.html">DOM table methods</a></li>
	<li><a href="tablebasics2.html">DOM - Refer to table cells</a></li>
	<li><a href="tablebasics3.html">innerHTML vs. DOM vs. cloneNode</a></li>
	<li><a href="tablebasics4.html">Add rows with fade in</a></li>
	<li><a href="tablebasics5.html">Add rows, and submit to PHP</a>
	<li><a href="tableaddrow.html">DOM Table Add Row</a></li>
	<li><a href="tabledeleterow.html">DOM Table Delete Row</a></li>
	<li><a href="tabledeleterow-calendar.html">DOM Table Delete Row - includes a calendar</a></li>
</ol>
<p>
For starters, I'd recommend <a href="tablebasics3.html">[3]</a>,
and if you've decided to use a DOM approach,
then check out the simple examples of
<a href="tablebasics1.html">[1]</a> and <a href="tablebasics2.html">[2]</a>.
Then you could move on the extended add/delete examples
<a href="tableaddrow.html">[6]</a> and <a href="tabledeleterow.html">[7]</a>.
If you're looking for some specific functionality also check out
<a href="tablebasics4.html">[4]</a>, <a href="tablebasics5.html">[5]</a>,
and <a href="tabledeleterow-calendar.html">[8]</a>
</p>
	</div>
</div>
 
<div id="linkmenu">
	<ul>
		<li><a href="../index.html">Home</a></li><li><a href="index.html">Tutorials</a></li><li><a href="htmljs.html">HTML / JavaScript</a></li>
<li class="youarehere"><a href="htmljs.html#tables">Tables</a></li>
	</ul>
	<ul class="listsection">	
		<li><a href="../feedback.html">feedback</a></li>
		<li><a href="../aboutus.html">about us</a></li>
		<li><a href="../legal.html">terms and conditions</a></li>
		<li><a href="../sitemap.html">site map</a></li>
	</ul>
	<div id="advert2">
			<script type="text/javascript"><!--
		google_ad_client = "pub-3639465516195777";
		google_ad_width = 120;
		google_ad_height = 600;
		google_ad_format = "120x600_as";
		google_ad_type = "text";
		google_ad_channel ="";
		google_color_border = "333333";
		google_color_bg = "000000";
		google_color_link = "FFFFFF";
		google_color_url = "999999";
		google_color_text = "CCCCCC";
		//--></script>
		<script type="text/javascript"
		  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
		</script>
		
	</div>
</div>
 
<div id="advert">
		
</div>
 
<div id="createInfo">
	<strong>About this page:</strong>
	<ul>
		<li>Author: Keith Jenci</li>
		<li>Created: Wednesday, March 10, 2004</li>
		<li>Last Updated: Wednesday, December 06, 2006</li>
	</ul>
</div>
 
<div id="copyright">
	Copyright &copy; 2006 <a href="http://www.novusoft.com/" class="externalLinkOurs">novusoft LLC</a>
</div>
 
<div id="advert3">
		<script type="text/javascript"><!--
		google_ad_client = "pub-3639465516195777";
		google_ad_width = 110;
		google_ad_height = 32;
		google_ad_format = "110x32_as_rimg";
		google_cpa_choice = "CAAQ_-KZzgEaCHfyBUS9wT0_KOP143Q";
		//--></script>
		<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
		</script>
</div>
 
</body>
</html>
