JavaScript:Tables

From virtualMV2015wiki
Jump to: navigation, search
 Home  JavaScript <

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.


Icon Objectives.png

Objectives

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

  • Understand table manipulation in JavaScript

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 table=document.getElementById("myTable");
    var row=table.insertRow(-1); // change to 0 to add at the top of the table
    var cell1=row.insertCell(0);
    var cell2=row.insertCell(1);
    cell1.innerHTML="R? C1";
    cell2.innerHTML="R? C2";
    }
  </script>
</head>
<body>
  <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>
</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);

Icon References.png References


JavaScript:Tables. (2017). In virtualMV's ( Michael Verhaart ) wiki. Retrieved December 12, 2017, from http://www.virtualmv.com/wiki/index.php?title=JavaScript%3ATables    (zotero)