Display JavaScript table on the load of a html web page - javascript

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);

Related

a ForEach function to make one tr to three tds and make a dinamic table

I need to make a little site that get some text boxes, ('Codigo' 'Nome' 'Documento') put on a array, that I already did, and make a a function with ForEach to create only one <tr> to three <td> I'm just not understand what I'm doing bad
function atualizarTabela() {
var tabelaBody = document.getElementById("corpo-tabela"); // corpo-tabela = tbody I need to clean it first
tabelaBody.innerHTML = "";
registros.forEach(function (registros) { // registros is my array that content the three text boxes
var createTr = document.createElement('tr');
for (var i = 0; i < registros[i]; i++) {
var createTd = document.createElement("td");
createTd.textContent = registro[i];
createTr.appendChild(createTd);
}
});
};
<body>
<table id="clientes">
<thead>
<tr>
<th>Codigo</th>
<th>Nome</th>
<th>Documento</th>
</tr>
</thead>
<tbody id="corpo-tabela">
</tbody>
</table>
<div id="bloco-dados">
<p>Código</p>
<input type="text" id="txtCodigo" name="Código">
<p>Nome</p>
<input type="text" id="txtNome" name="Nome">
<p>Documento</p>
<input type="text" id="txtDocumento" name="Documento"><br>
<input type="button" name="botao" id="btnSalvar" value="Salvar"><br>
<input type="button" name="botao2" id="btnNovo" value="Novo">
</div>
<script src="script.js" type="text/javascript"></script>
</body>
Thank you :)
Try removing the white space between function and the argument, and changing the argument to a dummy variable. So
registros.forEach(function(r) {
var createTr = document.createElement('tr');
for (var i = 0; i < r.length; i++) {
let createTd = document.createElement("td");
createTd.textContent = r[i];
createTr.appendChild(createTd);
tabelaBody.appendChild(createTr);
}
});

appendChild does not add new elements. It just replace the old elements to the new one (java script)

data variable's is 500. This variable has 500 ID of top stories of Hackers News.
and I am trying to add tr elements which shows the title of each ID and rank.
There is no problem if I only add one ID in the loop.
However, if I use more than one ID then the new tr element just replace the old tr element.
I wanted to display 500 top sorties but it only shows one story as you can see.
Is there any way to show 500 stories?
var itemlist = document.querySelector('.itemlist'); //tbody elements
var request = new XMLHttpRequest()
request.open('GET', 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty', true)
request.onload = function() {
// begin accessing JSON data here
var data = JSON.parse(this.response);
for (var j = 0; j < data.length; j++) {
var temp = data[j];
var id = 'https://hacker-news.firebaseio.com/v0/item/' + temp + '.json?print=pretty';
request.open('GET', id, true)
request.onload = function() {
var data = JSON.parse(this.response);
var tr = document.createElement('tr');
var td = document.createElement('td');
var td1 = document.createElement('td');
td.id = temp;
td.textContent = (j) + '.';
td1.textContent = data.title;
tr.appendChild(td);
tr.appendChild(td1);
itemlist.appendChild(tr);
console.log(id);
}
request.send();
}
}
request.send();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="CSS/style.css">
</head>
<body>
<table class="main" width="85%">
<tbody>
<tr>
<td bgcolor="#ff6600">
<table style="padding:2px;">
<tbody>
<tr>
<td style="width:18px;">
<a href="https://news.ycombinator.com/">
<img src="https://news.ycombinator.com/y18.gif" class="ylogo">
</a>
</td>
<td style="line-height:12px;height:10px">
<span class="mainmenu">
<span style="margin-right:7px;">
Hacker News
</span>
new
|
past
|
comments
|
ask
|
show
|
jobs
|
submit
</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="pagespace"></tr>
<tr>
<td>
<table>
<tbody class="itemlist">
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<script src="main.js"></script>
</body>
</html>

Javascript writing into Table not working

I just decided to code a little html file which should create a multiplication table with integers from "start" to "end". Start and End are set before in a HTMl Form...
I can give 2 numbers as input and the tr and td elements are create but accessing them by ClassName and filling them with innerHTML does somehow not work.
Here is the Code:
<html>
<head>
<title>Das groࠥ 1x1</title>
<meta charset="utf-8">
</head>
<script type="text/javascript">
function malnehmen(Wert1, Wert2) {
Ausgabe = Wert1 * Wert2;
return Ausgabe;
}
function tabelle() {
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(i = start; i < end+1; i++) {
Reihe = document.createElement("tr");
att = document.createAttribute("class");
att.value = i + "a";
Reihe.setAttributeNode(att);
document.getElementById("Darein").appendChild(Reihe);
for(ii = start; ii < end+1; ii++) {
Feld = document.createElement("td");
att2 = document.createAttribute("class");
att2.value = malnehmen(i, ii);
Feld.setAttributeNode(att2);
Reihe.appendChild(Feld);
}
}
}
function ausfuellen() {
tabelle();
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(a = start; a < end+1; a++) {
alert("Hier denn?");
document.getElementsByClassName(a + "a").innerHTML = a.toString();
for(aa = start; aa < end+1; aa++) {
multi = malnehmen(a, aa);
alert("Angekommen");
document.getElementsByClassName(multi).innerHTML = multi.toString();
}
}
}
</script>
<body>
<FORM name="printer">
<TABLE>
<tr>
<td>Beginnt bei:</td>
<td>
<input type="number" name="anfang" size="3">
</td>
</tr>
<tr>
<td>Endet bei:</td>
<td>
<input type="number" name="ende" size="3">
</td>
</tr>
<tr>
<td>
<input type="button" name="wassolldas" value="Erstellen" onclick="javascript: tabelle();">
</td>
</tr>
</TABLE>
</FORM>
<br>
<TABLE id="Darein" border="1">
</TABLE>
</body>
Does anybody know what I did wrong?
I built in 2 alerts just to see if the javascript part reaches the for loop but there is no pop up in browser.

How to hide and show table that is populated via a form

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.

How to send an HTML table,which is created dynamically using javascript,to a another page(servlet,jsp etc)?

How to send an HTML table, which is created dynamically using javascript, to a another page (servlet,jsp etc)?
My Code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript">
function createTable(numberOfRows) {
for ( var i = 1; i < numberOfRows; i++) {
var tr = document.createElement("tr");
var tableData = ['hello','world','hi','bye'];
for ( var j = 0; j < tableData.length; j++) {
var td = document.createElement("td");
var data = document.createTextNode(tableData[j]);
td.appendChild(data);
tr.appendChild(td);
}
document.getElementById("table1").appendChild(tr);
}
}
function sendTableToAnotherPage(){
// **what should be the code here,to fetch the table created using above function
//and send it to servlet or jsp page via AJAX.**
}
</script>
</head>
<body>
<table id="table1">
</table>
<button type="button" onclick="createTable(5)">Create Table</button>
<input type="button" value="Save" onclick="sendTableToAnotherPage()">
</body>
</html>
I am facing difficulty in fetching the table data from my servlet/jsp page.
Any help, would be highly appreciated.
If table and data is same then, you can pass table.innerHTML to another page.
example:
<script type="text/javascript">
function createTable(numberOfRows) {
for ( var i = 1; i < numberOfRows; i++) {
var tr = document.createElement("tr");
var tableData = ['hello','world','hi','bye'];
for ( var j = 0; j < tableData.length; j++) {
var td = document.createElement("td");
var data = document.createTextNode(tableData[j]);
td.appendChild(data);
tr.appendChild(td);
}
document.getElementById("table1").appendChild(tr);
}
}
function sendTableToAnotherPage(){
document.getElementById("table2").innerHTML = document.getElementById("table1").innerHTML;
}
</script>
<table id="table2" border="2">
</table>
<table id="table1">
</table>
<button type="button" onclick="createTable(5)">Create Table</button>
<input type="button" value="Save" onclick="sendTableToAnotherPage()">

Categories