I am getting an error on table population from json - javascript

I am attempting to populate a table from json data... I am getting an error message on inspect that states the $ is undefined and the resulting table is empty. Any thoughts are appreciated.
Here is the html:
<html manifest="trade.appcache">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="styles/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="leaflet-0.7.3/leaflet.css" type="text/css" />
<script type="text/javascript" src="leaflet-0.7.3/leaflet.js" rel="javascript" ></script>
<script type="text/javascript" src="js/jquery-1.11.3.min.js" rel="jquery" ></script>
<title>Top Trades</title>
</head>
<body style="margin: 0;padding: 0; display:none;">
<div id="deepbkg"></div>
<div id="fullscreen">
<audio autoplay><source src="audio/trade.wav" type="audio/wav"></audio>
<div id="system" class="mySlides" style="display: block;">
<table id="systems">
<thead>
<tr>
<th class="systems">
<h1>Top System Trades</h1>
</th>
<th>
<div>
<h2>Trade Value</h2>
</div>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="logo">
<img src="images/gamestop.png" style="width: 80%;" />
</div>
</div>
<div id="games" class="mySlides" style="display: none;">
<table id="games">
<thead>
<tr>
<th class="systems">
<h1>
Top Game Trades
</h1>
</th>
<th>
<div>
<h2>
PRO
</h2>
</div>
</th>
<th>
<div>
<h3>
Regular Value
</h3>
</div>
</th>
</tr>
</thead>
<tbody>
-->
</tbody>
</table>
</div>
<div id="electronics" class="mySlides" style="display: none;">
<table>
<thead>
<tr>
<th class="systems">
<h1>
Top Electronics Trades
</h1>
</th>
<th>
<div>
<h2>
Trade Value
</h2>
</div>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="cube">
<img src="images/cube.gif" style="width: 80%" />
</div>
<script src="js/divslide.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
var genericAJAXRequest = function(jsonFeedURL,paramData,callbackSuccess,callbackFailure,renderFunc) {
var paramData = (paramData !== undefined) ? paramData:{};
$.ajax({
url: jsonFeedURL,
type: 'post',
dataType: 'json',
data: paramData,
})
.done(function(data) {
// On success do this
callbackSuccess(data,renderFunc);
})
.fail(function(e) {
// on failure do these things
console.log("error");
console.log(e);
callbackFailure(e);
});
}
// If we get a good feed do this
var goodFeed = function(data,callback) {
console.log("Loaded Feed!");
console.log(data);
callback(data)
}
var badFeed = function(data) {
console.log("Did not load feed - error!");
console.log(data);
}
var dispSystem = function(data) {
$("#system table h1").text("Top System Trades");
$("#system table h2").text("Trade Value");
console.log(data.TopSystemTrades[0].name);
var row = "";
var loop = 0;
var len = data.TopSystemTrades.length;
var rowClass = "cost";
for (loop = 0; loop < len; loop++) {
row += '<tr><td class="title">'+data.TopSystemTrades[loop].name+'';
row += ' <span>'+data.TopSystemTrades[loop].pf+'</span></td>';
row += '<td class="'+rowClass+'">$'+parseFloat(data.TopSystemTrades[loop].price).toFixed(2).toLocaleString()+'</td></tr>';
}
$("#system table tbody").html(row);
console.log(row);
$("body").fadeIn(1000);
}
var dispGames = function(data) {
var table = $("#games");
$("#games table h1").text("Top Game Trades");
$("#games table h2").text("PRO");
$("#games table h3").text("Regular Value");
var row = "";
var loop = 0;
var len = data.TopGameTrades.length;
for (loop = 0; loop < len; loop++) {
row += '<tr><td class="title">'+data.TopGameTrades[loop].name+'';
row += ' <span>'+data.TopGameTrades[loop].pf+'</span></td>';
row += '<td class="cost">$'+parseFloat(data.TopGameTrades[loop].reg).toFixed(2).toLocaleString()+'</td>';
row += '<td class="cost">$'+parseFloat(data.TopGameTrades[loop].pro).toFixed(2).toLocaleString()+'</td></tr>';
}
$("#games table tbody").html(row);
console.log(row);
$("body").fadeIn();
}
var dispElectronics = function(data) {
var table = $("#electronics");
$("#electronics table h1").text("Top Electronics Trades");
$("#electronics table h2").text("Trade Value");
var row = "";
var loop = 0;
var len = data.TopElectronicsTrades.length;
for (loop = 0; loop < len; loop++) {
row += '<tr><td class="title">'+data.TopElectronicsTrades[loop].name+'';
row += ' <span>'+data.TopElectronicsTrades[loop].pf+'</span></td>';
row += '<td class="cost">$'+parseFloat(data.TopElectronicsTrades[loop].price).toFixed(2).toLocaleString()+'</td></tr>';
}
$("#electronics table tbody").html(row);
console.log(row);
$("body").fadeIn();
}
// Define our urls for the 3 different feeds
var topSystemsFeedURL = "data/top_system_trades_gde.json";
var topGameFeedURL = "data/top_game_trades_gde.json";
var topElectronicsFeedURL = "data/top_electronics_trades_gde.json";
// Make three different calls to load the json data from the urls, and render them to the html
genericAJAXRequest(topSystemsFeedURL, null, goodFeed, badFeed, dispSystem);
genericAJAXRequest(topGameFeedURL, null, goodFeed, badFeed, dispGames);
genericAJAXRequest(topElectronicsFeedURL, null, goodFeed, badFeed, dispElectronics);
});

Related

How to show JSON response in datatable using JavaScript [duplicate]

I have an HTML table with a header and a footer:
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
<tfoot>
</table>
I am trying to add a row in tbody with the following:
myTable.insertRow(myTable.rows.length - 1);
but the row is added in the tfoot section.
How do I insert tbody?
If you want to add a row into the tbody, get a reference to it and call its insertRow method.
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>initial row</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My Footer</td>
</tr>
</tfoot>
</table>
(old demo on JSFiddle)
You can try the following snippet using jQuery:
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
Basic approach:
This should add HTML-formatted content and show the newly added row.
var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
I think this script is what exactly you need
var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
You're close. Just add the row to the tbody instead of table:
myTbody.insertRow();
Just get a reference to tBody (myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.
A live demo is at jsFiddle.
Add rows:
<html>
<script>
function addRow() {
var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e = table.rows.length-1;
var l = table.rows[e].cells.length;
//x.innerHTML = " ";
for (var c=0, m=l; c < m; c++) {
table.rows[0].insertCell(c);
table.rows[0].cells[c].innerHTML = " ";
}
}
function addColumn() {
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].insertCell(0);
table.rows[r].cells[0].innerHTML = " ";
}
}
function deleteRow() {
document.getElementById("myTable").deleteRow(0);
}
function deleteColumn() {
// var row = document.getElementById("myRow");
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].deleteCell(0); // var table handle
}
}
</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>
<table id='myTable' border=1 cellpadding=0 cellspacing=0>
<tr id='myRow'>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
And cells.
let myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
let row = myTable.insertRow();
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
cell1.innerHTML = 1;
cell2.innerHTML = 'JAHID';
cell3.innerHTML = 23;
row = myTable.insertRow();
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell1.innerHTML = 2;
cell2.innerHTML = 'HOSSAIIN';
cell3.innerHTML = 50;
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #000;
padding: 10px;
}
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
</thead>
<tbody></tbody>
</table>
Add Column, Add Row, Delete Column, Delete Row. Simplest way
function addColumn(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
for(i=0;i<row.length;i++){
row[i].innerHTML = row[i].innerHTML + '<td></td>';
}
}
function deleterow(tblId)
{
var table = document.getElementById(tblId);
var row = table.getElementsByTagName('tr');
if(row.length!='1'){
row[row.length - 1].outerHTML='';
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
function myFunction(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].outerHTML;
table.innerHTML = table.innerHTML + row;
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].getElementsByTagName('td');
for(i=0;i<row.length;i++){
row[i].innerHTML = '';
}
}
table, td {
border: 1px solid black;
border-collapse:collapse;
}
td {
cursor:text;
padding:10px;
}
td:empty:after{
content:"Type here...";
color:#cccccc;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<p>
<input type="button" value="+Column" onclick="addColumn('tblSample')">
<input type="button" value="-Column" onclick="deleteColumn('tblSample')">
<input type="button" value="+Row" onclick="myFunction('tblSample')">
<input type="button" value="-Row" onclick="deleterow('tblSample')">
</p>
<table id="tblSample" contenteditable><tr><td></td></tr></table>
</form>
</body>
</html>
You can also use querySelector to select the tbody, then insert a new row at the end of it.
Use append to insert Node or DOMString objects to a new cell, which will then be inserted into the new row.
var myTbody = document.querySelector("#myTable>tbody");
var newRow = myTbody.insertRow();
newRow.insertCell().append("New data");
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
I have tried this, and this is working for me:
var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<div id="myDiv">
<label for="name">Name:</label>
<input
type="text"
name="myInput"
id="myInput"
placeholder="Name of expense"
size="50"
/><br /><br />
<label for="date">Date:</label>
<input type="date" id="myDate" name="myDate" />
<label for="amount">Amount:</label>
<input
type="text"
name="myAmount"
id="myAmount"
placeholder="Dollar amount ($)"
/><br /><br />
<span onclick="addRow()" class="addBtn">Add Expense</span>
</div>
<br />
<input type="button" value="Add Rows" onclick="addRows()" />
<!-- Optional position -->
<table id="myTable">
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Delete</th>
</tr>
<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>
</table>
<script>
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
function addRows() {
console.log("add rows");
document.getElementById("myTable").innerHTML += `<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>`;
}
</script>
</body>
</html>
$("#myTable tbody").append(tablerow);

Make table via value

How do I do that JavaScript will print in my HTML page a table via the value the user will choose?
That the JS script:
let numCol = document.getElementById('txtColumns').value;
let numRow = document.getElementById('txtRows').value;
let go = document.getElementById('btn');
let table = document.getElementById('table');
let td = "<td></td>" * numCol;
let tr = ("<tr>" + td + "</tr>") * numRow;
go.addEventListener('click', function(){
table.innerHTML = tr;
})
That the HTML code:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<table class="workTable">
<tr>
<td>
<input type="number" placeholder="Columns Number" id="txtColumns">
</td>
<td>
<input type="number" placeholder="Rows Number" id="txtRows">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button id="btn">
Print
</button>
</td>
</tr>
<div>
<table id="table">
<!--Here I want to print the table-->
</table>
</div>
</table>
<script src="script.js"></script>
</body>
</html>
At first I thought about that way with the script but its only appear as a NaN and not table...
The following syntax:
let td = "<td></td>" * numCol;
does not produce numCol cells, so the following syntax:
let tr = ("<tr>" + td + "</tr>") * numRow;
does not produce numRow rows also.
So, the whole source code should be:
let go = document.getElementById('btn');
let table = document.getElementById('table');
go.addEventListener('click', () => {
let numCol = document.getElementById('txtColumns').value; //Get the value of txtColumns at the button click moment.
let numRow = document.getElementById('txtRows').value;
let td = "",
tr = "";
for (let i = 0; i < numCol; i++) {
td = td + "<td></td>";
}
for (let i = 0; i < numRow; i++) {
tr = tr + "<tr>" + td + "</tr>";
}
table.innerHTML = tr;
})
<table class="workTable">
<tr>
<td>
<input type="number" placeholder="Columns Number" id="txtColumns">
</td>
<td>
<input type="number" placeholder="Rows Number" id="txtRows">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button id="btn">
Print
</button>
</td>
</tr>
<div>
<table id="table" border="1">
<!--Here I want to print the table-->
</table>
</div>
</table>

Get value from an ajax modal onclick

I m trying to get the value of a row id inside a modal called with Ajax.
I would like to get the row id (data-id) from the modal.
the JavaScript function "onRowClick" is working for the table in the main page but not for the one in the modal.
http://plnkr.co/edit/ehkd8L22KZb0xxCnubUb?p=preview
<DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/modalit#0.1.6/dist/MODALit.css">
<script src="https://cdn.jsdelivr.net/npm/modalit#0.1.6/dist/MODALit.min.js"></script>
</head>
<body>
<table id="table1">
<tr data-id="1"><td>Row 1</td></tr>
<tr data-id="2"><td>Row 2</td></tr>
<tr data-id="3"><td>Row 3</td></tr>
</table>
<hr />
<div style="color:green" id="row-value">-</div>
<hr />
<!-- Sets modal target -->
<button type="button" id="button" data-src="modal.html">Modal Open</button>
<script>
var modal = new MODALit({
el: '#button',
});
window.onload = onRowClick("table1", function (row) {
var rowid = row.getAttribute("data-id")
//alert(rowid);
document.getElementById("row-value").innerHTML = rowid;
})
function onRowClick(tableId, callback) {
var table = document.getElementById("table1"),
rows = table.getElementsByTagName("tr"),
i;
for (i = 0; i < rows.length; i++) {
table.rows[i].onclick = function (row) {
return function () {
callback(row);
};
}(table.rows[i]);
}
};
</script>
</body>
</html>
Ajax content (modal.html):
<table id="table2">
<tr data-id="1"><td>Row 1</td></tr>
<tr data-id="2"><td>Row 2</td></tr>
<tr data-id="3"><td>Row 3</td></tr>
</table>
<script>
window.onload = onRowClick("table2", function (row) {
var rowid = row.getAttribute("data-id")
//alert(rowid);
document.getElementById("row-value").innerHTML = rowid;
})
function onRowClick(tableId, callback) {
var table = document.getElementById("table2"),
rows = table.getElementsByTagName("tr"),
i;
for (i = 0; i < rows.length; i++) {
table.rows[i].onclick = function (row) {
return function () {
callback(row);
};
}(table.rows[i]);
}
};
http://plnkr.co/edit/ehkd8L22KZb0xxCnubUb?p=preview
How can i get the data-id of the row inside the modal ?

Error on Javascript code querying SharePoint list

I'm trying to return the contents of a SharePoint list to a HTML page using a JavaScript Query and JSON.
The line:
var query = "**http://collaboration-xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$select=DeviceID,Title**
does return the DeviceID and Title in browser.
However I don't quite know how I should construct the var query to return results from all the columns. What I've got is:
**var query = " xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$expand=Knownissues&$filter=DeviceID eq " + window.DeviceId + "";**
I've copied the 'windowsDeviceId' from a previous file which did work. Just having the first var query doesn't return anything and the second returns the attached screen grab. Error code.
The SharePoint columns are: Title, ServiceStatus, Devicetype and DeviceID
JavaScript:
function getDeviceKnownIssues() {
var txtTitle = "";
var txtStatus = "";
//var ServiceStatus = "";
//var Devicetype = "";
//var query = "http://collaboration-xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$select=DeviceID,Title",
var query = "http://collaboration-xxx.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$expand=Knownissues&$filter=DeviceID eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
var tempID = result.DeviceId;
var tempTitle = result.Title;
var StatusType = ServiceStatus;
txtTitle = txtTitle + "<p><a href='/sites/it/SystemInventory/SitePages/Service%20Catalogue.aspx?did=" + tempID + "'>" + tempTitle + "</a></p>";
txtStatus = "<p>" + StatusType + "</p>";
});
$('#knowntitle').append($(txtTitle));
$('#servivestatus').append(txtStatus);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
HTML
<html xmlns:mso="urn:schemas-microsoft-com:office:office"
xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"><head>
<script src="/jquery-1.10.1.min.js"></script>
<script src="/it/SystemInventory/SiteAssets/scripts/moment.min.js"></script>
<script src="/sites/it/SystemInventory/SiteAssets/getDevices.js"></script>
<script
src="/sites/it/SystemInventory/SiteAssets/getDeviceDetails.js"></script>
<script
src="/sites/it/SystemInventory/SiteAssets/getDeviceKnownIssues.js"></script>
<script type="text/javascript">
function parseQueryString(queryString)
{
var params = {}, queries, temp, i, l;
queries = queryString.split("&");
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
}
$(document).ready(function(){
function getDeviceID() {
if(typeof parseQueryString === "function") {
if(window.location.href.indexOf("?") >= 0) {
var qs = parseQueryString(window.location.href.split("?")[1])
window.DeviceId = qs.did;
getDeviceDetails();
getDeviceKnownIssues();
}
}
}
getDeviceID();
getDevices();
});
</script>
</head>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border- style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Devices</h1>
<div id="devices">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Details</h1>
<div id="devicedetails">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Overview</h1>
<div id="deviceoverview">
<div id="devicekind">
</div>
</td>
</tr>
</table>
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Accessories</h1>
<div id="deviceacc">
</div>
</td>
<td class="tg-yw4l">
<h1>Typical Usage</h1>
<div id="deviceuse">
</div>
</td>
<td class="tg-yw4l">
<h1>Spare Cell</h1>
<div id=" ">
</div>
</td>
</tr>
</table>
Known Issues
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Title</h1>
<div id="knowntitle">
</div>
</td>
<td class="tg-yw4l">
<h1>Service Status</h1>
<div id="servivestatus">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Type</h1>
<div id=" ">
</div>
</td>
</tr>
</table>

HTML Table page break print in Chrome

This problem is keeping me awake, is there a way to dynamically break a table, and show the header in the next page?
The fact is, it is a report and I can't know the number of rows it will show on the screen, I am using AngularJS to fetch the info and show on the screen.
Thats my page:
Page
While printing:
Print
This is my HTML Page
<!DOCTYPE html>
<html>
<head>
<!-- #INCLUDE VIRTUAL="/wvdf_bib/BIB/Includes/bHtmlHead.inc"-->
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-8">
<div class="col-xs-4">
<br />
<img class="col-xs-12" src="http://www.cargoweber.com/logos/profile/mepl-international-llc-logo-dubai-dub-916.png" />
</div>
<div class="col-xs-8">
<h3>Demo Company</h3>
<p>
John Smith<br />
demo#demo1.com<br />
http://www.demo1.com<br />
Phone: Tel: +1-908-301-6025
</p>
</div>
</div>
<div class="col-xs-4">
<h1>Rate quote</h1>
<h5>Created on 17 Jun 2015</h5>
<p>Document Number #LCL FCLJS150617003-1</p>
<small>As of date <strong>17 Jun 2015</strong></small><br />
<small>Valid until <strong>17 Jul 2015</strong></small>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<table class="table table-bordered">
<thead>
<tr>
<th class="col-xs-6">To</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="col-xs-5">
<br />
<img class="col-xs-12" src="http://www.cocacola.pt/19201201/jopt/post_images/standard/detail_lbITzYnZakM0pchLQsx9frA8wmHFdO.png" />
</div>
<div class="col-xs-7">
<h3>Coca Cola</h3>
<p>
http://www.cocacola.com
</p>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row>
<div class="col-xs-12">
<table class="table table-bordered">
<thead>
<tr>
<td colspan="7"></td>
<td colspan="3">Total Ocean Freight Sum Up</td>
</tr>
<tr>
<th>POL</th>
<th>Carrier</th>
<th>POD</th>
<th>VIA Port</th>
<th>Effective date</th>
<th>Expiry date</th>
<th>Transit time</th>
<th>Container20</th>
<th>Container40</th>
<th>Container40HC</th>
</tr>
</thead>
<tbody>
<tr>
<td>CNYTN Port of Yantian</td>
<td>NYK Line</td>
<td>USLAX Los Angeles</td>
<td></td>
<td>5/17/15</td>
<td>5/17/16</td>
<td>20 days</td>
<td>USD 1,235.00</td>
<td>USD 1,627.00</td>
<td>USD 1,627.00</td>
</tr>
<tr>
Another x rows
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
The problem is: I need the thead to be printed again on the new page, and I just can't get it to work =(
Does anyone know how I can solve this problem?
What is this table for? Printing? If so you could use JavaScript to create a new table from your existing table element. You could use JS to split the close and create a new table after X number of rows. The end result would be your original table, converted to multiple tables each holding X number of rows. That would give you the ability to print it with the same header on each page.
Here is what I use... You can modify it to your needs. Basically, just perform something to the extend of ....
<table id="myTable">
stuff
</table>
<div id="myNewTable"></div>
<script>
var myNewTable = separateTables('myTable','20');
document.getElementById("myNewTable").innerHTML = myNewTable;
function separateTables(table,rowLimit) {
/* Initialize variables */
var $table = $("#"+table);
var $headerCells = $table.find("thead th");
var $footerCells = $table.find("tfoot tr");
var $rows = $table.find("tbody tr");
var pageBreak = '<div style="page-break-before:always"> </div>';
var headers = [], footers = [], rows = [];
/* Add all header cells to headers array */
$headerCells.each(function() {
headers.push(this.outerHTML);
});
/* Add all rows in tbody to rows array */
$rows.each(function(){
rows.push(this.outerHTML);
});
/* Create table opening structure */
var el = document.getElementById(table);
var attr = [];
var vals = [];
for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++)
{
attr.push(attrs.item(i).nodeName);
vals.push(attrs.item(i).nodeValue);
}
var table = '<table ';
for(x=0;x<attr.length;x++)
{
//Ignore cellpadding & cellspacing - set both to zero to prevent issues
if(attr[x].toString().toLowerCase() == 'cellspacing' || attr[x].toString().toLowerCase() == 'cellpadding')
{
vals[x] = "0";
}
table += attr[x]+'="'+vals[x]+'" ';
}
table += '>';
/* Create header structure */
var header = '<thead><tr>';
for(x=0;x<headers.length;x++)
{
header += headers[x];
}
header += '</tr></thead>';
/* Create footer structure */
$footerCells.each(function(){
footers.push(this.outerHTML);
});
var footer = '<tfoot>';
for(x=0;x<footers.length;x++)
{
footer += footers[x];
}
footer += '</tfoot>';
/* Create our tables */
var newOutput = table + header + '<tbody>';
/* Loop over rows and create new table after count hits rowLimit */
var iCount = 0;
for (x=0;x<rows.length;x++)
{
iCount += 1;
newOutput += rows[x];
if(iCount == rowLimit)
{
newOutput += '</tbody></table>'+pageBreak+table+header+'<tbody>';
iCount = 0;
}
}
/* Close remaining table structure and return value */
newOutput += '</tbody>'+footer+'</table>';
return newOutput;
}
</script>
You should be using <th> instead of <td> in your <thead>. thead reference
<table class="table table-bordered">
<thead>
<tr>
<th class="col-xs-6">To</th>
</tr>
</thead>
<tbody></tbody>
</table>
In you css you can add
#media print {
thead {display: table-header-group;}
}

Categories

Resources