HTML table not displaying - javascript

I wanted to display a javascript object variable as a HTML table when a button with the id "stop" is pressed. I took some of my code for this problem from another question, however for some reason the browser doesn't even render the table.
Html
<table id="tbody"></table>
JavaScript
stop.addEventListener("click", () => {
container.style.display = "none";
stop.style.display = "none";
tbody.style.display = "block";
ratings = JSON.parse(sessionStorage.ratings);
for (let i = 0; i < ratings.length; i++) {
let tr = "<tr>";
tr += "<td>" + ratings[i].key.toString() + "</td>" + "<td>" + ratings[i].value.toString() + "</td></tr>";
tbody.innerHTML += tr;
}
});
I even specifically mention the display in my javascript file, as you can see:
tbody.style.display = "block";
If needed, you can find the full code here

#Ashish Kumar was right, the rating variable was an object. The TypeError (that came later) occurred because I was indexing the object like an array. Fixed that through the following edit in the event listener function :
stop.addEventListener("click", () => {
container.style.display = "none";
stop.style.display = "none";
tbody.style.display = "block";
ratings = JSON.parse(sessionStorage.ratings);
// console.log(ratings);
for (let i = 0; i < Object.keys(ratings).length; i++) {
let tr = "<tr>";
tr += "<td>" + Object.keys(ratings)[i] + "</td>" + "<td>" + Object.values(ratings)[i] + "</td></tr>";
tbody.innerHTML += tr;
}
});

stop.addEventListener("click", () => {
container.style.display = "none";
stop.style.display = "none";
ratings = JSON.parse(sessionStorage.ratings); // RATINGS IS OBJECT HERE
for (let i = 0; i < ratings.length; i++) { // ratings.length will not work as it's not an array
let tr = "<tr>";
/* Verification to add the last decimal 0 */
if (ratings[i].value.toString().substring(ratings[i].value.toString().indexOf('.'), ratings[i].value.toString().length) < 2)
ratings[i].value += "0";
/* Must not forget the $ sign */
tr += "<td>" + ratings[i].key.toString() + "</td>" + "<td>" + ratings[i].value.toString() + "</td></tr>";
/* We add the table row to the table body */
tbody.innerHTML += tr;
}
});
Please see the comments added at line 4 and 5

Related

Get id from path in SVG

So I have this SVG
https://github.com/Cphdat3sem2017f/StartcodeExercises/blob/master/JS/Countries_Europe.svg?short_path=6bcbfa5
I managed to hook up an eventListener and a fetch to get information on the countries when clicked on. This I have done by simply calling ex. document.getElementById("dk"). Is there a way and if so how, where i can get the id's inside the paths so I can loop through them and end up with only one call instead of one for each country?
Code:
import "bootstrap/dist/css/bootstrap.css";
const root = document.getElementById("root");
var svg = document.getElementById("svg");
const country = "https://restcountries.eu/rest/v1/alpha?codes=";
svg.addEventListener("load", function() {
var svgDoc = svg.contentDocument;
var countries = svgDoc.children;
for (let i = 0; i < countries.length; i++) {
//alert(countries[i].id);
countries[i].addEventListener("click", function(event) {
alert(countires[i]);
getCountryInfo(countries[i].id);
});
}
svgDoc.addEventListener("click", function(event) {
getCountryInfo(event.id);
});
var denmark = svgDoc.getElementById("dk");
denmark.addEventListener("click", function() {
getCountryInfo("dk");
});
var sweden = svgDoc.getElementById("se");
sweden.addEventListener("click", function() {
getCountryInfo("se");
});
var germany = svgDoc.getElementById("de");
germany.addEventListener("click", function() {
getCountryInfo("de");
});
var norway = svgDoc.getElementById("no");
norway.addEventListener("click", function() {
getCountryInfo("no");
});
var spain = svgDoc.getElementById("es");
spain.addEventListener("click", function() {
getCountryInfo("es");
});
var iceland = svgDoc.getElementById("is");
iceland.addEventListener("click", function() {
getCountryInfo("is");
});
});
function getCountryInfo(landCode) {
fetch(country + landCode)
.then(res => res.json()) //.then(res=>{ return res.json()})
.then(data => {
var table = "";
table +=
'<table border="1" style="border-spacing: 5px; table-layout: auto; width: 45%;">';
table += "<tr>";
table += "<th>Name</th>";
table += "<th>Capital</th>";
table += "<th>Also known as</th>";
table += "<th>Region</th>";
table += "<th>Population</th>";
table += "<th>Languages</th>";
table += "</tr>";
data.forEach(country => {
table += "<tr>";
table += "<td>" + country.name + "</td>";
table += "<td>" + country.capital + "</td>";
table += "<td>" + country.altSpellings + "</td>";
table += "<td>" + country.region + "</td>";
table += "<td>" + country.population + "</td>";
table += "<td>" + country.languages + "</td>";
table += "</tr>";
});
table += "</table>";
root.innerHTML = table;
});
}
As you can see we tried to get them by getting the children elements but we got stuck and couldn't seem to find answer.
Not sure what children resolves to in that context, but you can get to the paths directly via a query:
[...svgDoc.querySelectorAll('path')].forEach(path => {
path.addEventListener('click', e => {
alert(path.id);
})
})

How to get information in javascript to appear in html

The below code is supposed to make a shopping cart.However, I am unsure of how I do the conversion from javascript to html (I don't quite know how to describe it, sorry)
I am trying to have javascript build a table that has the values of the items within it, along with buttons to build the shopping cart. I initially was browsing the web to find how to do it, and thought that using document.getElementById().innerhtml would work, and referencing it in the body, however it seems that it is not functioning as intended.
<!DOCTYPE html>
<html>
<head>
<title>
ACME Corp Shopping Cart
</title>
<link rel = "stylesheet" href = "shopstyle.css">
<script type = "text/javascript", language = "javascript">
alert("YAS");
var products = [];
var cart = [];
//label individual products below in individual lists, and then have the product put through the product_setup function
var product1 = ["Anvil", "Premium Grade Iron", 119.99];
var product2 = ["Female Roadrunner Costume", "Guaranteed to attract Male Roadrunners", 54.99];
function product_setup(product){
var productID = product[0];
var product_desc = product[1];
var qty = 1;
var price = product[2];
var newProduct = {
product_id: null,
product_desc: null,
product_qty: 0,
product_price: 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
}
product_setup(product1);
product_setup(product2);
function product_table() {
var html = "<table border = '1|1' >";
html += "<td>Product Name</td>";
html += "<td>Product Description</td>";
html += "<td>Price</td>";
html += "<td>Add to Cart</td>";
for (var i = 0; i < products.length; i ++) {
html += "<tr>";
html += "<td>" + products[i].product_name + "</td>";
html += "<td>" + products[i].product_desc + "</td>";
html += "<td>" + products[i].product_price + "</td>";
html += "<td>" + <button type = 'submit' onclick = 'addCart(products[i].product_name, this)'>Add to Cart</button> + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("location1").innerHTML = html;
}
product_table();
function addCart(product_id) {
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
var cartItem = null;
for (var k = 0; k < cart.length; k++) {
if (cart[k].product.product_id == products[i].product_id) {
cartItem = cart[k];
cart[k].product_qty++;
break;
}
}
if (cartItem == null) {
cartItem = {
product: products[i],
product_qty: products[i].product_qty
};
cart.push(cartItem);
}
}
}
renderCartTable();
}
function subtractQuantity(product_id)
{
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart[i].product_qty--;
}
if (cart[i].product_qty == 0) {
cart.splice(i,1);
}
}
renderCartTable();
}
function addQuantity(product_id)
{
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart[i].product_qty++;
}
}
renderCartTable();
}
function removeItem(product_id)
{
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart.splice(i,1);
}
}
renderCartTable();
}
function renderCartTable() {
var html = '';
var ele = document.getElementById("location2");
ele.innerHTML = '';
html += "<table id='tblCart' border='1|1'>";
html += "<tr><td>Product ID</td>";
html += "<td>Product Description</td>";
html += "<td>Quantity</td>";
html += "<td>Price</td>";
html += "<td>Total</td>";
html += "<td>Action</td></tr>";
var GrandTotal = 0;
for (var i = 0; i < cart.length; i++) {
html += "<tr>";
html += "<td>" + cart[i].product.product_id + "</td>";
html += "<td>" + cart[i].product.product_desc + "</td>";
html += "<td>" + cart[i].product_qty + "</td>";
html += "<td>" + cart[i].product.product_price + "</td>";
html += "<td>" + parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty, 10) + "</td>";
html += "<td><button type='submit' onClick='subtractQuantity(\"" + cart[i].product.product_id + "\", this);'/>Subtract Item</button> &nbsp <button type='submit' onClick='addQuantity(\"" + cart[i].product.product_id + "\", this);'/>Add Item</button> &nbsp<button type='submit' onClick='removeItem(\"" + cart[i].product.product_id + "\", this);'/>Remove Item</button></td>";
html += "</tr>";
GrandTotal += parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty, 10);
}
document.getElementById("location3").innerHTML = GrandTotal;
html += "</table>";
ele.innerHTML = html;
}
renderCartTable();
</script>
</head>
<body>
<br>
<p id="location1"> </p>
<br/>
<h2> Shopping Cart </h2>
<p id="location2"> </p>
<h2>Grand Total:</h2>
<p id="location3"> </p>
</body>
</html>
It is always considered the best when you include your <script> tags after <body>. DOM elements that you try to access in your script are usually available only after the entire page has loaded. Your script should start running only after web page's body is created since you're expecting contents to be added to <body>

Updating table in html from javascript

I have been attempting to update a table, which is meant to be a "shopping cart." However, upon pressing the "add to cart button", my table does not update.
The html for the javascript just uses getElementbyId, and both tables appear on the screen when I run the html file.
I'm still fairly new to javascript, so I was hoping someone with more experience could double check for me to see that I have what I need.
var html = "<table border = '1|1' >";
html += "<td>Product Name</td>";
html += "<td>Product Description</td>";
html += "<td>Price</td>";
html += "<td>Add to Cart</td>";
for (var i = 0; i < products.length; i ++) {
html += "<tr>";
html += "<td>" + products[i].product_name + "</td>";
html += "<td>" + products[i].product_desc + "</td>";
html += "<td>" + products[i].product_price + "</td>";
html += "<td>" + <button type = 'submit' onclick = 'addCart(products[i].product_name, this)'>Add to Cart</button> + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("location1").innerHTML = html;
function addCart(product_id) {
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
var cartItem = null;
for (var k = 0; k < cart.length; k++) {
if (cart[k].product.product_id == products[i].product_id) {
cartItem = cart[k];
cart[k].product_qty++;
break;
}
}
if (cartItem == null) {
var cartItem = {
product: products[i],
product_qty: products[i].product_qty
};
cart.push(cartItem);
}
}
}
renderCartTable();
}
//RenderCartTable & its functions
function addCart(product_id) {
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
var cartItem = null;
for (var k = 0; k < cart.length; k++) {
if (cart[k].product.product_id == products[i].product_id) {
cartItem = cart[k];
cart[k].product_qty++;
break;
}
}
if (cartItem == null) {
cartItem = {
product: products[i],
product_qty: products[i].product_qty
};
cart.push(cartItem);
}
}
}
}
The code pulls from a list of products, and produces a table with the name, description, and price of the item, along with the Add to Cart button. The button is meant to add the item to a different list, called "cart".
Any and all help appreciated. Thanks for your time!
Below is all of the code--
<!DOCTYPE html>
<html>
<body>
<br/>
<p id="location1"> </p>
<br/>
<h2> Shopping Cart </h2>
<p id="location2"> </p>
<h2>Grand Total:</h2>
<p id="location3"> </p>
<script type="text/javascript", language="javascript", src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
var products = [];
var cart = [];
//label individual products below in individual lists, and then have the product put through the product_setup function
var product1 = ["Anvil", "Premium Grade Iron", 119.99];
var product2 = ["Female Roadrunner Costume", "Guaranteed to attract Male Roadrunners", 54.99];
function product_setup(product) {
var productID = product[0];
var product_desc = product[1];
var qty = 1;
var price = product[2];
var newProduct = {
product_id: null,
product_desc: null,
product_qty: 0,
product_price: 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
}
product_setup(product1);
product_setup(product2);
function product_table() {
var html = "<table border = '1|1' >";
html += "<td>Product Name</td>";
html += "<td>Product Description</td>";
html += "<td>Price</td>";
html += "<td> </td>";
for (var i = 0; i < products.length; i ++) {
html += "<tr>";
html += "<td>" + products[i].product_id + "</td>";
html += "<td>" + products[i].product_desc + "</td>";
html += "<td>" + products[i].product_price + "</td>";
html += "<td>" + "<button type = 'submit' onclick = 'addCart(products[i].product_id, this)'>Add to Cart</button>" + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("location1").innerHTML = html;
}
product_table();
function subtractQuantity(product_id) {
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart[i].product_qty--;
}
if (cart[i].product_qty == 0) {
cart.splice(i,1);
}
}
renderCartTable();
}
function addQuantity(product_id) {
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart[i].product_qty++;
}
}
renderCartTable();
}
function removeItem(product_id) {
for (var i = 0; i < cart.length; i++) {
if (cart[i].product.product_id == product_id) {
cart.splice(i,1);
}
}
renderCartTable();
}
function renderCartTable() {
var html = '';
var ele = document.getElementById("location2");
ele.innerHTML = '';
html += "<table id='tblCart' border='1|1'>";
html += "<tr><td>Product ID</td>";
html += "<td>Product Description</td>";
html += "<td>Quantity</td>";
html += "<td>Price</td>";
html += "<td>Total</td>";
html += "<td>Action</td></tr>";
var GrandTotal = 0;
for (var i = 0; i < cart.length; i++) {
html += "<tr>";
html += "<td>" + cart[i].product.product_id + "</td>";
html += "<td>" + cart[i].product.product_desc + "</td>";
html += "<td>" + cart[i].product_qty + "</td>";
html += "<td>" + cart[i].product.product_price + "</td>";
html += "<td>" + parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty, 10) + "</td>";
html += "<td><button type='submit' onClick= 'subtractQuantity(\"" + cart[i].product.product_id + "\", this);'>Subtract Item</button> &nbsp <button type='submit' onClick='addQuantity(\"" + cart[i].product.product_id + "\", this);'/>Add Item</button> &nbsp<button type='submit' onClick='removeItem(\"" + cart[i].product.product_id + "\", this);'/>Remove Item</button></td>";
html += "</tr>";
GrandTotal += parseFloat(cart[i].product.product_price) * parseInt(cart[i].product_qty, 10);
}
document.getElementById("location3").innerHTML = "$ " + GrandTotal;
html += "</table>";
ele.innerHTML = html;
}
renderCartTable();
function addCart(product_id) {
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
var cartItem = null;
for (var k = 0; k < cart.length; k++) {
if (cart[k].product.product_id == products[i].product_id) {
cartItem = cart[k];
cart[k].product_qty++;
break;
}
}
if (cartItem == null) {
cartItem = {
product: products[i],
product_qty: products[i].product_qty
};
cart.push(cartItem);
}
}
}
renderCartTable();
}
</script>
</body>
</html>
You want this:
html += "<td>" + "<button type = 'submit' onclick = 'addCart(\"" + products[i].product_id + "\")'>Add to Cart</button>" + "</td>";
In your case, when clicking the button onclick = 'addCart(products[i].product_id), The i inside products[i] is only known inside the product_table(){...} so when called outside it's context, i is undefined. There was an attempt to pass the context in using this, while a good idea, that i would be knows inside addCart and not where addCart is being called (global context, or window) and since the for-loop continues that i would not have the correct value.
So instead we pass the whole product-id in as a string and it works.
So how could we get rid of the ugly escape-strings?
Template literals are almost always prettier html += `<td><button type = 'submit' onclick = 'addCart("${products[i].product_id}")'>Add to Cart</button></td>`; but it's a ES6 feature (so check what browsers you need to support).
I think binding the click-event to the container, and outside the renderfunction would be prettier. Since we only need one listener that way. As opposed to creating new onclicks on every call to renderCartTable.
var clickHandler = function(evt){
if(evt.target.nodeName === 'BUTTON'){
// Check that we have the right button (from a class perhaps)
// parse out data from event.target.parentElement
// or pass in product-id via a data attribute
}
};
document.getElementById("location1").addEventListener('click', clickHandler)
I think you are passing product_name to the addCart and checking it against product_id.
Try putting debugger; and check the value you get in the function.
try this, hope this works:
var html = "<table border = '1|1' >";
html += "<td>Product Name</td>";
html += "<td>Product Description</td>";
html += "<td>Price</td>";
html += "<td>Add to Cart</td>";
for (var i = 0; i < products.length; i ++) {
html += "<tr>";
html += "<td>" + products[i].product_name + "</td>";
html += "<td>" + products[i].product_desc + "</td>";
html += "<td>" + products[i].product_price + "</td>";
html += "<td>" + "<button type = 'submit' onclick = 'addCart("+products[i].product_id+", this)'>Add to Cart</button>" + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("location1").innerHTML = html;
function addCart(product_id) {
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
var cartItem = null, cartItemId;
if (cart.length > 0)
for (var k = 0; k < cart.length; k++) {
if (cart[k].product.product_id == products[i].product_id) {
cartItem = cart[k];
cart[k].product_qty++;
break;
}
}
if (cartItem == null) {
var cartItem = {
product: products[i],
product_qty: products[i].product_qty + 1
};
cartItemId = cart.push(cartItem);
}
}
}
renderCartTable();
}
also make sure products array looks like this:
var products = [
{product_id: 0, product_name: "item1", product_desc: "desc1", product_price: 100, product_qty: 0},
{product_id: 1, product_name: "item2", product_desc: "desc2", product_price: 200, product_qty: 0},
{product_id: 2, product_name: "item3", product_desc: "desc3", product_price: 300, product_qty: 0},
{product_id: 3, product_name: "item4", product_desc: "desc4", product_price: 400, product_qty: 0}
];
functions wont work on appended data, so better use JQuery or something and do it like this.
$('#myTable').on('click','.addToCart',function(){
//perform something...
});
You can also do
$(document).on('click','.addToCart',function(){
//perform something...
});

Generate HTML table and load it in div element

I'd like to load a HTML table into a div-element (id="resultDataDistancesTable") - but the generated string isn't processed (no matter if I use html(), append() or innerHTML). There is no error in the console.
When I paste the console.log(..) output directly to the HTML page I get the table that I want - so why doesn't my JavaScript code work? Is something wrong with the string?
var response = {"distances":[[0,4569,17264,6074,4986,12430,10936,11729,11280,23714,19112,24070,24974,25809,24157,27636,27323,15690,27970,22152],[4837,0,9160,1879,1872,12492,10755,15237,14468,21251,16649,17650,20574,23346,21694,31144,30831,13227,23141,19689],[17807,9681,0,8419,14314,25164,23427,28206,27140,11709,17204,18205,21130,23901,22249,30219,29906,4147,23696,10294],[6156,1736,8271,0,3191,12812,8437,16555,14788,22085,17483,18484,21408,24180,22528,30498,30185,14061,23975,20523],[5438,1642,14335,3147,0,12796,11058,15838,14771,20785,16183,17184,20108,22880,21228,31745,31432,12761,22674,19223],[12266,13371,25607,10970,13329,0,1842,20750,6094,32057,27455,28455,31380,34152,32500,37248,36935,24033,37581,30495],[10434,11651,16093,8428,11608,1842,0,19509,7092,30336,25734,26735,29659,32431,30779,35416,35104,22312,35750,28774],[12355,15633,28328,17138,16050,19963,20849,0,6457,34778,30176,26719,27624,33122,31702,30285,29973,26754,30619,33216],[11054,14433,26669,14776,14391,6088,9450,10828,0,33119,28517,36279,37184,35214,33562,39846,39533,25095,40179,31557],[21936,20085,11649,19803,18444,29293,27556,32335,31269,0,2943,8201,8702,10694,9042,17012,16699,8876,11268,5269],[19141,17291,16426,17009,15649,26499,24762,29541,28475,2924,0,5407,6515,9365,7713,15683,15370,14852,9082,6033],[22777,19065,18201,18783,17424,28274,26536,25758,31348,8188,5556,0,2979,5144,6115,10994,10681,16626,5493,10239],[23722,21760,20895,21478,20118,30968,29231,26703,32292,8634,6627,2994,0,2715,3388,4505,4192,19321,3110,11521],[29801,24947,24082,24665,23305,34155,32417,32782,38371,9673,8179,5136,2704,0,2345,4277,3964,22508,1703,15331],[25139,23289,22424,23007,21647,32497,30760,30797,34473,8016,6521,6129,3394,2340,0,5174,4862,20850,3779,13673],[26964,30242,30040,31748,30660,36952,35458,29945,35534,16511,10598,10365,4526,4274,5182,0,336,28466,1821,15492],[26628,29906,29704,31412,30324,36616,35122,29609,35198,16175,10262,10029,4190,3938,4846,313,0,28130,1485,15156],[16108,9772,4136,13975,12616,23466,21728,26507,25441,8931,10916,11916,14841,17613,15961,23930,23617,0,17407,7516],[27163,30441,23429,24012,22653,37151,35657,30144,35733,11168,9161,5495,3089,1703,3746,1686,1373,21855,0,14055],[22592,20741,10188,20459,19100,29949,28212,32991,31925,5369,5909,10225,11565,14414,12762,20732,20419,7415,14131,0]]};
buildResultTableDistances();
function buildResultTableDistances() {
var tbl;
var tr_head = "<table><tr><td>distances [meters]</td>";
for (var i = 0; i < 20; i++) {
tr_head += "<td><b>" + "dummy" + "</b></td>";
}
tr_head += "</tr>";
tbl = tr_head;
for (var i = 0; i < 20; i++) {
var row = "<tr><td><b>" + "dummy" + "</b></td>";
for (var ii = 0; ii < 20; ii++) {
row += "<td>" + response.distances[i][ii] + "</td>";
}
row += "</tr>";
tbl += row;
}
tbl += "</table>";
console.log(tbl);
$('#resultDataDistancesTable').html(tbl);
}
I suspect you forgot to insert the HTML or including jQuery, because it works fine here. If you want, to do this solely in JavaScript by adding the element in jQuery:
$(document.body).append('<div id="resultDataDistancesTable"></div>');
var response = {"distances":[[0,4569,17264,6074,4986,12430,10936,11729,11280,23714,19112,24070,24974,25809,24157,27636,27323,15690,27970,22152],[4837,0,9160,1879,1872,12492,10755,15237,14468,21251,16649,17650,20574,23346,21694,31144,30831,13227,23141,19689],[17807,9681,0,8419,14314,25164,23427,28206,27140,11709,17204,18205,21130,23901,22249,30219,29906,4147,23696,10294],[6156,1736,8271,0,3191,12812,8437,16555,14788,22085,17483,18484,21408,24180,22528,30498,30185,14061,23975,20523],[5438,1642,14335,3147,0,12796,11058,15838,14771,20785,16183,17184,20108,22880,21228,31745,31432,12761,22674,19223],[12266,13371,25607,10970,13329,0,1842,20750,6094,32057,27455,28455,31380,34152,32500,37248,36935,24033,37581,30495],[10434,11651,16093,8428,11608,1842,0,19509,7092,30336,25734,26735,29659,32431,30779,35416,35104,22312,35750,28774],[12355,15633,28328,17138,16050,19963,20849,0,6457,34778,30176,26719,27624,33122,31702,30285,29973,26754,30619,33216],[11054,14433,26669,14776,14391,6088,9450,10828,0,33119,28517,36279,37184,35214,33562,39846,39533,25095,40179,31557],[21936,20085,11649,19803,18444,29293,27556,32335,31269,0,2943,8201,8702,10694,9042,17012,16699,8876,11268,5269],[19141,17291,16426,17009,15649,26499,24762,29541,28475,2924,0,5407,6515,9365,7713,15683,15370,14852,9082,6033],[22777,19065,18201,18783,17424,28274,26536,25758,31348,8188,5556,0,2979,5144,6115,10994,10681,16626,5493,10239],[23722,21760,20895,21478,20118,30968,29231,26703,32292,8634,6627,2994,0,2715,3388,4505,4192,19321,3110,11521],[29801,24947,24082,24665,23305,34155,32417,32782,38371,9673,8179,5136,2704,0,2345,4277,3964,22508,1703,15331],[25139,23289,22424,23007,21647,32497,30760,30797,34473,8016,6521,6129,3394,2340,0,5174,4862,20850,3779,13673],[26964,30242,30040,31748,30660,36952,35458,29945,35534,16511,10598,10365,4526,4274,5182,0,336,28466,1821,15492],[26628,29906,29704,31412,30324,36616,35122,29609,35198,16175,10262,10029,4190,3938,4846,313,0,28130,1485,15156],[16108,9772,4136,13975,12616,23466,21728,26507,25441,8931,10916,11916,14841,17613,15961,23930,23617,0,17407,7516],[27163,30441,23429,24012,22653,37151,35657,30144,35733,11168,9161,5495,3089,1703,3746,1686,1373,21855,0,14055],[22592,20741,10188,20459,19100,29949,28212,32991,31925,5369,5909,10225,11565,14414,12762,20732,20419,7415,14131,0]]};
buildResultTableDistances();
function buildResultTableDistances() {
var tbl;
var tr_head = "<table><tr><td>distances [meters]</td>";
for (var i = 0; i < 20; i++) {
tr_head += "<td><b>" + "dummy" + "</b></td>";
}
tr_head += "</tr>";
tbl = tr_head;
for (var i = 0; i < 20; i++) {
var row = "<tr><td><b>" + "dummy" + "</b></td>";
for (var ii = 0; ii < 20; ii++) {
row += "<td>" + response.distances[i][ii] + "</td>";
}
row += "</tr>";
tbl += row;
}
tbl += "</table>";
$('#resultDataDistancesTable').html(tbl);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultDataDistancesTable"></div>
I could replicate your issue using Plunker: http://plnkr.co/edit/QxklTx0R6WcYwpRIpd98 has the fix. You weren't waiting for the DOM to be loaded before attempting to append to the object. See line 3:
$("document").ready(function() {
buildResultTableDistances();
});
Should work then.

Loop every nth item and fill the blanks

I want to build an HTML table string for every 10 items in a Javascript array, and if there are less than 10 items in the last iteration I want to fill it with empty rows.
How do I achieve this?
var array_of_items; //array of items
//make a html table string every 10 items
var table = '<table>';
table += '<tr><td>' + item1 + '</td></tr>';
table += '<tr><td>' + item2 + '</td></tr>';
.
.
.
table += '<tr><td>' + item10 + '</td></tr>';
table += '</table>';
//make second table
table = '<table>';
table += '<tr><td>' + item11 + '</td></tr>';
table += '<tr><td>' + item12 + '</td></tr>'; //array ends here
table += '<tr><td></td></tr>';
.
.
.
table += '<tr><td></td></tr>';
table += '</table>';
$('#table_div').html(table);
var table = '';
var numTables = Math.ceil(array_of_items.length / 10); //determine how many tables
for (var i=0;i<numTables;i++){
table +='<table>';
for (var j=0;j<10;j++){
(array_of_items[i*10+j] ? table +='<tr><td>' + array_of_items[i*10+j] + '</td></tr>' : table +='<tr><td></td></tr>');
}
table +='</table>';
}
var ln = items.length;
var lnten = ln + 10 - ln%10;
var container = $('#table_div');
for (var j = 0; j < lnten; j++) {
var tbl;
if (j % 10 == 0)
tbl = $('<table/>');
var tr = $('<tr/>');
var td = $('<td/>');
if (j < ln)
td.text(items[j]);
tr.append(td);
tbl.append(tr);
if (j % 10 == 0)
container.append(tbl);
}
jsfiddle DEMO
I think you're looking for this
for (var i = 0; i < array_of_items.length; i+=10) {
var table = '<table>';
for (var j = i; j < i+10; ++j) {
if (array_of_items[j] === 'undefined') {
table += '<tr><td></td></tr>';
}
else table += '<tr><td>' + array_of_items[j] + '</td></tr>';
}
table += '</table>';
}

Categories