VirtualMV/JavaScript/TableObject
Introduction
Overview
- 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.
By the end of this page you will be able to:
|
Refer to: http://www.w3schools.com/jsref/dom_obj_table.asp
Creating a Table and adding rows
<html> <head> <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); varCell1.innerHTML=document.myForm.txtFName.value; varCell2.innerHTML=document.getElementById("txtLName").value; } </script> </head> <body> <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> </table> <p><button type="button" onclick="displayResult()">Insert new row</button></p> </form> </body> </html>
For insertRow 0 = insert at the top of the table, -1 = at the bottom and a number indicates which row,
Ref: http://www.w3schools.com/jsref/met_table_insertrow.asp
Displaying in a pop-up window
function fnDisplayHire() { var varMyTable = document.getElementById('myTable'); winMsg=window.open("","_blank"); winMsg.document.write("<html><head><title>Display table</title>"); winMsg.document.write("</head>"); winMsg.document.write("<body>"); winMsg.document.write("<table border='1'>" + varMyTable.innerHTML + "</table>"); winMsg.document.write("</body></html>"); }
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
alert(document.getElementById("myTable").rows.length);
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
References
virtualMV | Superquick wiki guide | Please give me some feedback |
VirtualMV/JavaScript/TableObject. (2024). In WikiEducator/VirtualMV wiki. Retrieved November 21, 2024, from http:https://wikieducator.org/VirtualMV/JavaScript/TableObject (zotero)
|