I'm trying to render a table using javascript. The following is the html and javascript. I'm tyring to draw the same table that I draw using HTML in javascript. However, the script doesn't seem to render.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table width = "50%" border = "1" align = "center">
<thead>
<th>ONE</th>
<th>TWO</th>
<th>THREE</th>
</thead>
<tbody>
<tr>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
<tr>
<td>r2c1</td>
<td>r2c2</td>
<td>r2c3</td>
</tr>
</tbody>
</table>
</body>
<script type = "text/javascript">
var table = document.createElement("table");
table.width = "50%";
table.border = "1";
table.align = "center";
//create the table header
var thead = document.createElement("thead");
table.appendChild(thead);
//create the cells inside thead
thead.insertRow(0);
thead.rows[0].insertCell(0);
thead.rows[0].cells[0].appendChild(document.createTextNode("ONE"));
thead.rows[0].insertCell(1);
thead.rows[0].cells[1].appendChild(document.createTextNode("TWO"));
thead.rows[0].insertCell(2);
thead.rows[0].cells[2].appendChild(document.createTextNode("THREE"));
//create the table body
var tbody = document.createElement("tbody");
table.appendChild(tbody);
//create the cells inside tbody
tbody.insertRow(0);//do you start from zero here or 1?
tbody.rows[0].insertCell(0);
tbody.rows[0].cells[0].appendChild(document.createTextNode("r1c1"));
tbody.rows[0].insertCell(1);
tbody.rows[0].cells[1].appendChild(document.createTextNode("r1c2"));
tbody.rows[0].insertCell(2);
tbody.rows[0].cells[2].appendChild(document.createTextNode("r1c3"));
//now we make the 2nd row
tbody.insertRow(1);
tbody.rows[1].insertCell(0);
tbody.rows[1].cells[0].appendChild(document.createTextNode("r2c1"));
tbody.rows[1].insertCell(1);
tbody.rows[1].cells[1].appendChild(document.createTextNode("r2c2"));
tbody.rows[1].insertCell(2);
tbody.rows[1].cells[2].appendChild(document.createTextNode("r2c3"));
//now we make the third row
tbody.insertRow(2);
tbody.rows[2].insertCell(0);
tbody.rows[2].cells[0].appendChild(document.createTextNode("r3c1"));
tbody.rows[2].insertCell(1);
tbody.rows[2].cells[1].appendChild(document.createTextNode("r3c2"));
tbody.rows[2].insertCell(2);
tbody.rows[2].cells[2].appendChild(document.createTextNode("r3c3"));
</script>
</html>
How do I show the 2nd table? Which parts of my code are wrong? I'm purposely not using the DOM methods.
gratefully
saad
Error:
You have created element, but you haven't appended it to the body.
document.getElementsByTagName("body")[0].appendChild(table);
Another Solution:
If you can use jQuery, it will be much less complex and easier too.
<script type = "text/javascript">
var table = $("<table>", {width: '50%', border: 1, align: 'center'});
//create the cells inside thead
var row = $("<tr />").append("<th>One</th>").append("<th>Two</th>").append("<th>Three</th>");
//create the table header
var thead = $("<thead />").append(row);
table.append(thead);
//create the table body
var tbody = $("<tbody />");
//create the cells inside tbody
var r1 = $("<tr />").html("<td>r1c1</td><td>r1c2</td><td>r1c3</td>");
tbody.append(r1);
//now we make the 2nd row
var r2 = $("<tr />").html("<td>r2c1</td><td>r2c2</td><td>r2c3</td>");
tbody.append(r2);
//now we make the third row
var r3 = $("<tr />").html("<td>r3c1</td><td>r3c2</td><td>r3c3</td>");
tbody.append(r3);
table.append(tbody);
$("body").append(table);
</script>
CSS
th {font-weight: bold; text-align: center;}
Fiddle: http://jsfiddle.net/FWGsk/1/
Related
The following HTML file contains an add button. When clicked, it should add a row. When I inspect the code, I find the rows added under the thead not the tbody tag. Why is that? how to avoid this?
addButton = document.getElementById("add-button");
table = document.getElementById("data-table");
addButton.addEventListener('click', add, false);
function add() {
var tableLength = table.length;
var row = table.insertRow(tableLength);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = "col1";
col2.innerHTML = "col2";
}
var delLink = document.getElementById("delete-link");
delLink.addEventListener('click', del, false);
function del() {
var rowstoDelete = table.querySelectorAll("tbody tr");
[].slice.call(rowstoDelete).forEach(function(row) {
row.remove()
});
}
<table align="center" cellspacing=1 cellpadding=1 id="data-table" border=1 class="data-table">
<thead>
<tr id="head" class="head">
<th class="head">Name</th>
<th class="head">Action</th>
</tr>
<tr id="initial-row" class="initial-row">
<th><input type="text" id="text-field"></th>
<th><input type="button" class="add-button" id="add-button" value="Add"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<a id="delete-link" href="#"> Delete all rows Except the first two</a>
check my fiddle here
enter link description here
What you didnt did is to see specifically for tbody. Answered here How to insert row in HTML table body in javascript?
addButton=document.getElementById("add-button");
table=document.getElementById("data-table");
addButton.addEventListener('click',add,false);
function add()
{
var tableLength=table.length;
var row = table.getElementsByTagName('tbody')[0].insertRow(tableLength);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML="col1";
col2.innerHTML="col2";
}
var delLink = document.getElementById("delete-link");
delLink.addEventListener('click',del,false);
function del()
{
var rowstoDelete = table.querySelectorAll("tbody tr");
[].slice.call(rowstoDelete).forEach(function(row) {
row.remove()
});
}
Below is a form when submitted displays the content in a table.
What works
Content is successfully transferred via form to table.
What is not working
I wanted to hide the table when the page loads and be displayed only after the form is submitted.
I tried #myTableData {visibility: hidden;} in css and then I tried plugging (.style.visibility="visible";) Javascript in my addtable function to display the table but it does not work. I am not sure if I am understanding this right.
Also how do I control the display of the table (like width, background color, font etc). I added (td.style.width = '200px'; but I don't see any changes).
CSS or JS for controlling table ?
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
1) In function addRow add table.style.visibility = "visible"; ,to display the table, right after var table = document.getElementById("myTableData");.
2) To set styles like width you can can use setAttribute method.
document.getElementById('myTableData').setAttribute("style","width:200px");
Note: I can't see where you make use of addTable function, maybe this is why some of styles are not setted when you want.
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
table.style.visibility = "visible";
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
I don't have the rep to comment so I can't ask for details, but just in case you can use jquery, you can hide and show stuff like this:
$(function(){
$("#add").click(function() {
var name = $('#name').val();
var domain = $('#domain').val();
var url = $('#url').val();
$('#hidey').show();
$('#nametd').html(name);
$('#domtd').html(domain);
$('#urltd').html(url);
})
});
https://jsfiddle.net/6dxLsnL4/
Or trigger on form submit instead of click if you want, but there, you might want to consider ajax, because then you can make sure the form is processed on the server side before displaying the results.
I am trying to display a populated table on a html page using javascript.
This is what I have so far:
table.js - contains my function and data for the table
var ORDER = { orders: [] };
function Order(ref, grower, item) {
this.order_reference = ("o" + ref);
this.grower_reference = grower;
this.item_ordered = item;
}
var order1 = new Order(1, "grower2", "item");
ORDER.orders.push(order1);
function addTable(){
var table = document.createElement("TABLE");
table.setAttribute("id", "myTable");
document.body.appendChild(table);
for (var i=0; i<ORDER.length; i++) {
var row = document.createElement("TR");
var refCell = document.createElement("TD");
var growerCell = document.createElement("TD");
var itemCell = document.createElement("TD");
var ref = document.createTextNode(refArray[i]);
var grower = document.createTextNode(growerArray[i]);
var item = document.createTextNode(itemArray[i]);
refCell.appendChild(ref);
growerCell.appendChild(grower);
itemCell.appendChild(item);
table.appendChild(row);
}
}
html page
<!DOCTYPE html>
<html lang = "en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body id="contracts">
<div id="wrapper">
<div id="mytable">
</div>
</div>
<div id="footer">
<table id= "footer" style="width: 100%">
<tr>
<td valign="bottom">Company Name <br> Tel Num <br> Location, Postcode</td>
<td> <button onclick="addTable()"> Click me </button></td>
<td align="right" valign="bottom"><a href="#">Home <a href="#">About <a href="#">Help <a href="#">Contact</td>
</tr>
</table>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="table.js"></script>
</body>
</html>
Firstly, I wanted to display the table on the click of a button. Secondly, I want to display the table as soon as the html page is loaded.
How would I go about this?
Sorry if its not a good question, or if there is lots missing. I'm quite new to this so sort of just using different tutorials and putting stuff together ...
You have a few problems:
In your loop for (var i = 0; i < ORDER.length; i++) { should be for (var i = 0; i < ORDER.orders.length; i++) {
refArray, growerArray, itemArray are undefined
You are not appending the tds to the tr
Be sure to look at https://developer.chrome.com/devtools/docs/javascript-debugging and to check your console for errors.
The following example adds the table after the page is loaded, and also when you click the button.
var ORDER = {
orders: []
};
function Order(ref, grower, item) {
this.order_reference = ("o" + ref);
this.grower_reference = grower;
this.item_ordered = item;
}
var order1 = new Order(1, "grower2", "item");
ORDER.orders.push(order1);
function addTable(orders) {
var table = document.createElement("TABLE");
table.setAttribute("id", "myTable");
document.body.appendChild(table);
for (var i = 0; i < orders.length; i++) {
var order = orders[i];
var row = document.createElement("TR");
var refCell = document.createElement("TD");
var growerCell = document.createElement("TD");
var itemCell = document.createElement("TD");
row.appendChild(refCell);
row.appendChild(growerCell);
row.appendChild(itemCell);
var ref = document.createTextNode(order.order_reference);
var grower = document.createTextNode(order.grower_reference);
var item = document.createTextNode(order.item_ordered);
refCell.appendChild(ref);
growerCell.appendChild(grower);
itemCell.appendChild(item);
table.appendChild(row);
document.body.appendChild(document.createElement('hr'));
}
}
window.addEventListener('load', function() {
addTable(ORDER.orders)
});
<div id="wrapper">
<div id="mytable"></div>
<div id="footer">
<table id="footer" style="width: 100%">
<tr>
<td valign="bottom">Company Name
<br />Tel Num
<br />Location, Postcode</td>
<td>
<button onclick="addTable(ORDER.orders)">Click me</button>
</td>
<td align="right" valign="bottom">
Home About Help Contact
</td>
</tr>
</table>
</div>
</div>
<hr />
The first thing you need to consider, is that you can't add elements to the DOM until it has loaded.
Your addTable function builds the table and appends it to the <body> element. This needs to be called when the page is ready and the DOM has been loaded.
window.addEventListener('load', addTable);
However, I reckon that you probably don't want it to be attached to the bottom of the <body>? I'm guessing it should go inside <div id="mytable"></div>?
The following adjustments would allow for that behaviour.
var table = document.createElement("TABLE"),
container = document.getElementById('mytable');
table.setAttribute("id", "myTable");
container.appendChild(table);
I have the following problem. I would like to add some data to a table using label values (in this case 7 & 5) but every time I try to add a value, the cells show the message "undefined". The main idea is to create a table which values are going to be used to draw a bar chart (graph) using the highcharts library
<h2>Add Row in JavaScript</h2>
<table id="table" cellspacing="0" border="1">
<tbody>
<tr>
<td>Name</td>
<td>Address</td>
</tr>
</tbody>
</table>
<button onclick="javascript:addRow('table')">Add row</button>
<br></br>
<label id="txt1" value="7" text="a">label 1</label>
<label id="txt2" value="5" text="b">label 2</label>
Script:
function addRow(id){
var label = ($("#txt1").val());
var label2 = ($("#txt2").val());
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
var data1 = document.createElement("td");
data1.appendChild(document.createTextNode(label.value));
var data2 = document.createElement("td");
data2.appendChild(document.createTextNode(label2.value));
row.appendChild(data1);
row.appendChild(data2);
tbody.appendChild(row);
}
Example in JFiddle
Code
Highcharts library
Code
It seems you have taken label instead of textbox, anyway below is working code.
function addRow(id) {
var label = ($("#txt1").attr("value"));
var label2 = ($("#txt2").attr("value"));
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
var data1 = document.createElement("td");
data1.appendChild(document.createTextNode(label));
var data2 = document.createElement("td");
data2.appendChild(document.createTextNode(label2));
row.appendChild(data1);
row.appendChild(data2);
tbody.appendChild(row);
}
I need to dynamically create tables one beside the other. So I have created a table(outer) and am trying to generate columns dynamically on button click. In each of these columns I will create the actual tables(inner) I need, so that in the end they appear side by side.
But I'm stuck at creating columns for the bigger table. Take a look at the code and it will be clear.
Any solution in JS is appreciated. Thanks in advance
<html>
<head>
<script type="text/javascript">
function add() {
var table = document.getElementById('foo');
var rowCount = table.rows.length;
var row =document.getElementById('rowl');
var max=table.rows[0].cells.length;
var cnum;
if(max==0){
cnum=0;
}else{
cnum=max+1;
}
var cell1 = row.insertCell(cnum);
cell1.innerHTML = "<table id='tabl'"+
cnum+
"' border=2 bordercolor='RED'><tr><th>Material "+
(cnum+1)+
"</th></tr><tr><td>bdfgher</td></tr><tr><td>fdgerh</td></tr></table>";
}
</script>
</head>
<body>
<button type="button" onclick="add()">Add cell</button>
<table id="foo" border=1 bordercolor="BLUE">
<tr id="rowl"></tr>
</table>
</body>
</html>
var cell = document.createElement("td");
document.getElementById("rowl").appendChild(cell);
Of course, you should add your other elements (inner table) in the cell element.
It may help you a little :)
<html>
<head>
<script>
var c=-1;
function displayResult()
{
var firstRow=document.getElementById("tr_1");
//var x=firstRow.insertCell(-1);
//x.innerHTML="New cell"
var cell1 = firstRow.insertCell(c++);
cell1.innerHTML = "<table id='tabl'"+
cnum+
"' border=2 bordercolor='RED'><tr><th>Material "+
(cnum+1)+
"</th></tr><tr><td>bdfgher</td></tr><tr><td>fdgerh</td></tr></table>";
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr id='tr_1'></tr>
</table>
<br>
<button type="button" onclick="displayResult()">Insert cell</button>
</body>
</html>