A function to print a html table using Javascript - javascript

I need the write() function to print a html table using JavaScript,the column names should be First name,Last name and Email sequentially.I can't get the names to print in the table.Don't know what i m doing wrong.Below is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Address Book</title>
<script type="text/javascript">
function addressBookItem (fname, lname, email) {
this.fname= fname;
this.lname = lname;
this.email = email;
}
addressBookItem.prototype.write = function() {
var table=document.getElementById("myTable");
var row=table.insertRow(-1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
cell1.innerHTML=this.fname;
cell2.innerHTML=this.lname;
cell3.innerHTML=this.email;
}
</script>
</head>
<body>
<script type="text/javascript">
var aB1 = new addressBookItem('Roger', 'Williams', 'rwilliams#gmail.com');
var aB2 = new addressBookItem ('Rose', 'Schultz', 'rose_s#earthlink.net');
aB1.write();
aB2.write();
</script>
<table id="myTable" border="1">
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Email Address</td>
</tr>
</table>
</body>
</html>

Related

Bootstrap table style not applying to JS generated table

Hello I am new to website development (started a couple of days ago).
I have some programming experience using Python and C#.
I have been trying to generate an HTML table using JS and apply it a Bootstrap css style.
I can't seem to get it to work.
What I get:
What I want:
I hope to get something that styles like this (simplified from: w3schools)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Basic Table</h2>
<p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p>
<table class="table">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
</table>
</div>
</body>
</html>
My html page looks like this:
<!DOCTYPE html>
<html>
<head>
<title>CSVParser</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<script type="text/javascript" src="../scripts/csvToHtml.js"></script>
<form onsubmit="return processFile();" action="#" name="myForm" id="aForm" method="POST">
<input type="file" id="myFile" name="myFile"><br>
<input type="submit" name="submitMe" value="Process File">
</form>
<table id="myTable" class="table"></table>
</div>
</body>
</html>
and the JS script is:
function processFile() {
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
if (theFile) {
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e) {
var content = myReader.result;
var lines = content.split("\r");
for (var count = 0; count < lines.length; count++) {
var row = document.createElement("tr");
var rowContent = lines[count].split(",");
for (var i = 0; i < rowContent.length; i++) {
if (count == 0) {
var cellElement = document.createElement("th");
} else {
var cellElement = document.createElement("td");
}
var cellContent = document.createTextNode(rowContent[i]);
cellElement.appendChild(cellContent);
row.appendChild(cellElement);
}
myTable.appendChild(row);
}
}
myReader.readAsText(theFile);
}
return false;
}
The csv data file I load looks like this:
TestA,TestB,TestC,TestD
Alpha,0.551608445,0.807554763,54.8608682
Beta,0.191220409,0.279946678,57.55254144
This is the generated HTML table from the JS:
<table id="myTable" class="table">
<tr>
<th>TestA</th>
<th>TestB</th>
<th>TestC</th>
<th>TestD</th>
</tr>
<tr>
<td>Alpha</td>
<td>0.551608445</td>
<td>0.807554763</td>
<td>54.8608682</td>
</tr>
<tr>
<td>Beta</td>
<td>0.191220409</td>
<td>0.279946678</td>
<td>57.55254144</td>
</tr>
<tr>
<td></td>
</tr>
</table>
You are missing a <tbody> element around all the <tr> Elements. thats it. if you insert this additionally you are fine with your layout.
I've changed your code quite a bit but here is a working example:
<!DOCTYPE html>
<html>
<head>
<title>CSVParser</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#" name="myForm" id="aForm" method="POST">
<input type="file" id="myFile" name="myFile"><br>
<input type="button" name="submitMe" value="Process File" onclick="processFile();">
</form>
<table id="myTable" class="table"></table>
</div>
</body>
<script type="text/javascript">
function processFile() {
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
if (theFile) {
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e) {
var content = myReader.result;
var lines = content.split("\r");
var tbody = document.createElement("tbody");
for (var count = 0; count < lines.length; count++) {
var row = document.createElement("tr");
var rowContent = lines[count].split(",");
for (var i = 0; i < rowContent.length; i++) {
if (count == 0) {
var cellElement = document.createElement("th");
} else {
var cellElement = document.createElement("td");
}
var cellContent = document.createTextNode(rowContent[i]);
cellElement.appendChild(cellContent);
row.appendChild(cellElement);
}
tbody.appendChild(row);
}
table.appendChild(tbody);
}
myReader.readAsText(theFile);
}
return false;
}
</script>
</html>
Working example without having to upload a file
<!DOCTYPE html>
<html>
<head>
<title>CSVParser</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#" name="myForm" id="aForm" method="POST">
<textarea id="myFile" name="myFile">TestA,TestB,TestC,TestD
Alpha,0.551608445,0.807554763,54.8608682
Beta,0.191220409,0.279946678,57.55254144</textarea><br>
<input type="button" name="submitMe" value="Process File" onclick="processFile();">
</form>
<table id="myTable" class="table"></table>
</div>
</body>
<script type="text/javascript">
function processFile() {
var table = document.querySelector("#myTable");
var content = $("#myFile").val();
var lines = content.split("\n");
var tbody = document.createElement("tbody");
for (var count = 0; count < lines.length; count++) {
var row = document.createElement("tr");
var rowContent = lines[count].split(",");
for (var i = 0; i < rowContent.length; i++) {
if (count == 0) {
var cellElement = document.createElement("th");
} else {
var cellElement = document.createElement("td");
}
var cellContent = document.createTextNode(rowContent[i]);
cellElement.appendChild(cellContent);
row.appendChild(cellElement);
}
tbody.appendChild(row);
}
table.appendChild(tbody);
return false;
}
</script>
</html>
ALSO! You are using myTable.appendChild(row); in your code although you've never initialized any myTable variable.
Load your js script just before the </body> end tag.
Now you are loading the JavaScript before the browser has read all your tags and by then it can't find the elements you are querying in your script.
<body>
<div class="container">
<form onsubmit="return processFile();" action="#" name="myForm" id="aForm" method="POST">
<input type="file" id="myFile" name="myFile"><br>
<input type="submit" name="submitMe" value="Process File">
</form>
<table id="myTable" class="table"></table>
</div>
<!-- Here's the difference -->
<script type="text/javascript" src="../scripts/csvToHtml.js"></script>
</body>

jQuery $.each iterating through firebase array twice

I am trying to use jQuery with firebase on the web and am building a quick table of users and tickets. The users and tickets are displaying properly, however they are iterated over twice, in that the table contains the same users and tickets twice. I am not sure what is happening.`
var users = ["Nick","Peter"];
var rows = "";
var number = 0;
//Sync all changes
dbRefAllUsers.on('value', function(snap) {
console.log("#Run",number+1);
jQuery.each(users, function(index,name){
console.log(name);
rows += "<tr><td>" + name + "</td><td>" + snap.child(name).child("tickets").val() + "</td></tr>";
console.log(rows);
});
$(rows).appendTo("#ticketTable tbody");
return head.innerText = JSON.stringify(snap.val(), null, 3);
});`
HTML:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title></title>
</head>
<body>
<h1 id="head"></h1>
<script src="https://www.gstatic.com/firebasejs/3.6.7/firebase.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="./app.js"></script>
<table id="ticketTable" style="font-size:18px;">
<thread>
<tr>
<th>Users</th>
<th>Tickets</th>
</tr>
</thread>
<tbody>
</tbody>
</table>
</body>
</html>

Using variables from the same js file in 2 html files with JQuery

I am trying to get my variable I have saved to display on a table I have created on another page. I get the information from the user from a form, and have a button that is clicked and fires off to save the values into variables. My problem is that I can't change the inner html on the other page with the variable I have saved. I am using 1 js file and 2 html files. I can only use js/jquery, html, and css. here is my code:
loanpage.html
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Super Awesome Loan Guys</title>
<link rel="stylesheet" type="text/css" href="loanpage.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="loanpage.js"></script>
</head>
<body>
<div class="bg" id="text-center">
<div class="companytitle"><span class="dollar">$</span>uper Awe<span class="dollar">$</span>ome Loan Guy<span class="dollar">$</span></div>
<div>
<form action="infopage.html">
<h4>Loan Amount:</h4>
<input type="text" id="loanamount" name="loanamount"><br>
<input type="radio" id="12month" name="time">12 Months
<input type="radio" id="18month" name="time">18 Months
<input type="radio" id="24month" name="time">24 Months
<h4>Name:</h4><input id="namefield" type="text" name="firstlastname">
<h4>Phone:</h4><input id="phonefield" type="text" name="phonennumber">
<h4>Email:</h4><input id="emailfield" type="text" name="email">
<h4>Zip Code:</h4><input id="zipfield" type="text" name="zipcode"><br>
</form>
<button type="button">Submit</button>
</div>
</div>
</body>
</html>
infopage.html
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Super Awesome Loan Guys Loan Information</title>
<link rel="stylesheet" type="text/css" href="loanpage.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="loanpage.js"></script>
</head>
<body>
<div class="bg" id="text-center">
<h1>Here is the info you submitted!</h1>
<table>
<tr>
<th>Name</th>
<th>Phone Number</th>
<th>Email Address</th>
<th>Zip Code</th>
<th>Loan Amount</th>
<th>Loan Duration</th>
<th>Interest</th>
</tr>
<tr>
<td id="displayName">1</td>
<td id="displayPhone">1</td>
<td id="displayEmail">1</td>
<td id="displayZip">1</td>
<td id="displayAmount">1</td>
<td id="displayDuration">1</td>
<td id="displayInterest">1</td>
</tr>
</table>
</div>
</body>
</html>
loanpage.js
//js code
var name = "";
var phone="";
var email="";
var zip="";
var loan=0;
var loanrate=12.0;
var loanlen=0;
//Jquery code
$(document).ready(function (){
$("#submitbutton").click(function(){
loan = parseFloat($("#loanamount").val());
if ($("#12month").is(':checked')){
loanlen = 12;
}
else if ($("#18month").is(':checked')){
loanlen = 18;
}
else if ($("#24month").is(':checked')){
loanlen = 24;
}
name = $("#namefield").val();
phone = $("#phonefield").val();
email = $("#emailfield").val();
zip = $("#zipfield").val();
document.getElementById("displayName").innerHTML(name);
document.getElementById("displayPhone").innerHTML(phone);
document.getElementById("displayEmail").innerHTML(email);
document.getElementById("displayZip").innerHTML(zip);
document.getElementById("displayAmount").innerHTML(loan);
document.getElementById("displayDuration").innerHTML(loanlen);
document.getElementById("displayInterest").innerHTML(loanrate);
});
});
Local Storage is your best bet.
// Save data to the current local store
localStorage.setItem("username", "John");
// Access some stored data
alert( "username = " + localStorage.getItem("username"));
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

how to use datatable with dynamically created table

I have a jsp which onload calls a js in which a table is created dynamically.
The situation is that I have never worked on jquery earlier, all I know is javascript.
I made two scenarios:
case one : when I create static table on the jsp page itself it works flawlessly.
case two : when I try to load the same table which is created by dynamic javascript it fails.
Case I Working code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/createDynamicTable.js"></script>
<script type="text/javascript" src="../js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#testTable').dataTable();
});
</script>
</head>
<body>
<div id="tableDataDiv">
<table id="testTable">
<thead>
<th>h1</th>
<th>h2</th>
<th>h3</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Case II Not Working code
jsp code
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/createDynamicTable.js"></script>
<script type="text/javascript" src="../js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#testTable').dataTable();
});
</script>
</head>
<body onload="getTableData();">
<div id="tableDataDiv">
</div>
</body>
</html>
js code
function getTableData(){
var tableDataDivObj = document.getElementById("tableDataDiv");
var tableObj = document.createElement("table");
tableObj.id = 'testTable';
// header
var theadObj = document.createElement("thead");
var thObj = document.createElement("th");
thObj.innerHTML = 'h1';
theadObj.appendChild(thObj);
thObj = document.createElement("th");
thObj.innerHTML = 'h2';
theadObj.appendChild(thObj);
thObj = document.createElement("th");
thObj.innerHTML = 'h3';
theadObj.appendChild(thObj);
tableObj.appendChild(theadObj);
// body
var tbodyObj;
var trObj;
var tdObj;
tbodyObj = document.createElement("tbody");
var count = 1;
for(i = 0; i < 3; i++){
trObj = document.createElement("tr");
for(j = 0; j < 3; j++){
tdObj = document.createElement("td");
tdObj.innerHTML = count;
trObj.appendChild(tdObj);
count++;
}
tbodyObj.appendChild(trObj);
}
tableObj.appendChild(tbodyObj);
tableDataDivObj.appendChild(tableObj);
}
Once the table is created dynamically, we append it to the div on the jsp page.
Kindly suggest any modification, suggestions so that I can get this code work.
this is just an example I have created of my real application .
which involves complete mvc, where table data is retrived from the service methods and dao files. I am able to get the data into the table(I made sure after getting an alert on jsp page). I am not able to use datatable on the id of the table.
Thanks in advance!
When your dataTables initialization is run, the table doesn't exist yes. You can fix by moving the $('#testTable').dataTable(); after the table has been initialized.
$(tableObj).dataTable();
at the end of the getTableData function (which should be defined in your $(document).ready callback.
Yon can add datatable to your dynamically created table in javascript.Code is as follows:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
function createTable(){
var myTableDiv = document.getElementById("box");
var table = document.createElement('TABLE');
table.id='tableId'
table.border='1';
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(1);
cell.innerHTML = "<b>Name</b>";
cell1.innerHTML = "<b>Age</b>";
cell2.innerHTML = "<b>Email</b>";
cell3.innerHTML = "<b>address</b>";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<3; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<4; j++){
var td = document.createElement('TD');
td.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
$("#tableId").dataTable();
}
</head>
<body>
<input type="button" onclick="createTable();" value="CreateTable" /></br>
<div id="box">
</div>
</body>
</html>
Please call jquery method once your table get created by dynamic javascript.
You can find example here how to create dynamically:
http://datatables.net/release-datatables/examples/data_sources/js_array.html

Rolling up the content of html rows in javascript

I have a table with 20 lines, and I wanted their rows to go up (skipping the first row line) after 1 minute the page has loaded.
Ex:
Initial
row1
row2
row3
First steo
row2
row3
row1
second state
row3
row1
row2
Final step
row1
row2
row3
I was doing something like this, but I don't know how to replace the content of the rows.
And if possible do it slowly (gradual would be great but now essencial)
function roll()
{
var oRows = document.getElementById('ultNot').getElementsByTagName('tr');
var iRowCount = oRows.length;
//repeat this iRowCount-1?
for (i=iRowCount; i=2;;i--){
var tempRow= oRows[i];
var origRow;
if (i=rowCount) {
origRow=oRows[1];
} else {
origRow=cRows[i-1];
}
var tempContent=origRow;
//replace the contents of the rows
}
}
thanks a lot for any help
Thanks Razvan, that did the trick. The whole code to do what I wanted (which is to roll the complete group of rows 1 time after 40 seconds):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<table id="ultNot" style="border: 1">
<tbody>
<tr>
<td>First row</td>
</tr>
<tr>
<td>Second row</td>
</tr>
<tr>
<td>Third row</td>
</tr>
<tr>
<td>Fourth row</td>
</tr>
<tr>
<td>Fifth row</td>
</tr>
</tbody>
</table>
<input type="button" onclick="iniciaScroll()" value="Click" />
<script type="text/javascript">
window.setTimeout(function() {
iniciaScroll();
;
}, 40000);
</script>
<script type="text/javascript">
var interval;
var cont = 0;
var sizeTable = document.getElementById('ultNot').rows.length;
function roll() {
var table = document.getElementById('ultNot');
var rows = table.rows;
var firstRow = rows[1];
var clone = firstRow.cloneNode(true);
table.tBodies[0].appendChild(clone);
table.tBodies[0].removeChild(firstRow);
cont++;
if (cont == (sizeTable - 1)) {
clearInterval(interval);
cont = 0;
}
}
function iniciaScroll() {
interval = window.setInterval(function() {
roll();
}, 3000);
}
</script>
<!-- end: portal_latestthreads -->
</body>
</html>
There probably is a better way but this is all I could come up with until now :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function roll() {
var table = document.getElementById('myTable');
var rows = table.rows;
var firstRow = rows[0];
var clone = firstRow.cloneNode(true);
table.tBodies[0].appendChild(clone);
table.tBodies[0].removeChild(firstRow);
}
</script>
</head>
<body>
<table id="myTable" style="border: 1">
<tbody>
<tr><td>First row</td></tr>
<tr><td>Second row</td></tr>
<tr><td>Third row</td></tr>
<tr><td>Fourth row</td></tr>
<tr><td>Fifth row</td></tr>
</tbody>
</table>
<input type="button" onclick="roll()" value="Click"/>
</body>
</html>

Categories

Resources