From WikiEducator
Jump to: navigation, search



  • Creating tables in JavaScript requires the use of the DOM table Object Model. As <table> and <tr> are read only attributes in Internet Explorer, this means you can't use innerHTML to create rows in a table. To manage this JavaScript has a DOM Table object model.

VmvIcon Objectives.png

By the end of this page you will be able to:

  • Understand table manipulation in JavaScript

Refer to:

Creating a Table and adding rows

<script type="text/javascript">
  function displayResult() {
    var objTable=document.getElementById("myTable");
    var varRow=objTable.insertRow(-1); // change to 0 to add at the top of the table
    var varCell1=varRow.insertCell(0);
    var varCell2=varRow.insertCell(1);
<form name="myForm">
   <p>Enter Your Firstname:<input type="text" name="txtFName" value="" /><br />  
      Enter Your Lastname:<input type="text" id="txtLName" value="" /></p> 
  <table id="myTable" border="1">
    <tr><td>R1 C1</td><td>R1 C2</td></tr>
    <tr><td>R2 C1</td><td>R2 C2</td></tr>
  <p><button type="button" onclick="displayResult()">Insert new row</button></p>

For insertRow 0 = insert at the top of the table, -1 = at the bottom and a number indicates which row,


Displaying in a pop-up window

function fnDisplayHire() {
    var varMyTable = document.getElementById('myTable');"","_blank");
	winMsg.document.write("<html><head><title>Display table</title>");
	winMsg.document.write("<table border='1'>" + varMyTable.innerHTML + "</table>");

Displaying (or accessing) a cell in the table

     winMsg.document.write("<p>" + varMyTable.rows[1].cells[0].innerHTML + "<p>");

And to display the number of rows


Table: Trouble shooting

Problem: When Add to Table button is pressed the row is added then the screen flashes and the row disappears.

Solution, in the code you probably have the wrong input type (type = submit). The correct type is button:

  <input type="button" value="Add to Table" onClick="fnaddToTable()">

Problem:When you click [Add] a very small row may be added with no data.

Solution: Check the names in the js match the html names. Try commenting out until you find the offending one if you need to.

Problem:You get cannot read property of undefined...

Solution: Check you are using name or id correctly in form (document.myform.... = name) getElementById = id

VmvIcon References.png References

virtualMV  |  Superquick wiki guide  |  Please give me some feedback

VirtualMV/JavaScript/TableObject. (2022). In WikiEducator/VirtualMV wiki. Retrieved August 12, 2022, from http:    (zotero)