Dynamically Creating HTML table from JS array with jQuery - javascript

I would like to dynamically create an HTML table using jQuery. I have a JS array filled with data.
I have tried the following and it doesn't work, nothing shows up. What am I doing wrong?
Javascript code
for(var i = 0; i < cycleArr.length; i++) {
var strTable = "<tr>"
for(var j = 0; j < cycleArr[i]; j++) {
var strTable = strTable + "<td>";
var strTable = strTable + cycleArr[i];
var strTable = strTable + "</td>";
}
var strTable = strTable + "</tr>";
}
$('#model_table').append(strTable);
HTML code
<div id="model_table">
</div>

Assuming that cycleArr is a 2-dimensional array (for everything else this code wouldn't make a lot of sense, but correct me if I'm wrong), I found the following issues with your code:
You are comparing j with cycleArr[i] which is probably an array, instead of cycleArr[i].length.
In the inner loop you are accessing cycleArr[i] instead of cycleArr[i][j].
You are overwriting your strTable variable in each iteration of the outer loop because you are assigning <tr> instead of appending it.
You are declaring your variable strTable over and over again. It should be declared only once.
You are inserting <tr>s and <td>s into a <div> instead of a <table>. While this may be intended, I assumed it is not.
Here is a working version of your code:
var cycleArr = [['a', 'b', 'c'], ['d', 'e', 'f']];
var strTable = "";
for(var i = 0; i < cycleArr.length; i++) {
strTable += "<tr>"
for(var j = 0; j < cycleArr[i].length; j++) {
strTable += "<td>";
strTable += cycleArr[i][j];
strTable += "</td>";
}
strTable += "</tr>";
}
$('#model_table').append(strTable);
table {
border-collapse: collapse;
}
td {
border: 1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="model_table">
</table>
Also, you wrote that you have a "JSON array", but it would appear you have a JS (JavaScript) array. A JSON array would be a string which encodes an array (you wouldn't be able to iterate over it before parsing it which makes it no longer JSON). I took the liberty to correct your post to avoid confusion.

I put the code into one html file. Below is the code. Take note, that you need to allow the:
strTable - continue looping by adding += . Just simplify var strTable = strTable + "" from your code above.
The idea here is, you have column and row. First you'll loop the direction from left to right, then if the row is completed, you need to go to next row.
<div id="model_table">&npsp;</div> <!-- result here -->
<script type="text/javascript">
var cycleArr = [[1,2,3,4,5], [6,7,8,9,10]];
var strTable = '<table border="1" cellpadding="5">';
for(var i = 0; i < cycleArr.length; i++) {
strTable += "<tr>";
for(var j = 0; j < cycleArr[i].length; j++) {
strTable += '<td>' + cycleArr[i][j] + '</td>';
}
strTable += "</tr>";
}
strTable += '</table>';
document.getElementById('model_table').innerHTML = strTable;
</script>

Related

Add a header row and a time column to a generated HTML table with jQuery

I have these two working JavaScript functions
https://github.com/cryptomanxxx/Random2DArrayPlusHtmlTable
https://cryptomanxxx.github.io/Random2DArrayPlusHtmlTable/
that 1) generates some random data 2) creates a HTML table for such data. There are two problems.
1) The HTML table column headings (the first row in the HTML table) are missing. Which is the simples way to add a row (should be the first row) with column headings to the HTML table? The column heading row should say something generic like this: variable 1, variable 2, variable 3 etc etc
2) The HTML table does not have a column with timestamps. A new column (first column) with timestamps would also be nice like: time 1, time 2, time 3 etc etc
It is obvious that I have not managed to understand how the code works because if I did it would be easy to modify the code. The complexity is overwhelming.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JavaS.js"></script>
<meta charset="utf-8" />
<style>
table {
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
</body>
<script> htmlTable(RandomArray(8, 4)); </script>
</html>
function RandomArray(rows, cols) {
var arr = [];
for (var i = 0; i < rows; i++) {
arr.push([]);
arr[i].push(new Array(cols));
for (var j = 0; j < cols; j++) {
arr[i][j] = Math.random();
}
}
console.log(arr);
return arr;
}
function htmlTable(d) {
var data = d;
var html = '<table><thead><tr></tr></thead><tbody>';
for (var i = 0, len = data.length; i < len; ++i) {
html += '<tr>';
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
html += '<td>' + data[i][j] + '</td>';
}
html += "</tr>";
}
$(html).appendTo('#div1') ;
}
Don't stress about the complexity, it gets easier the longer you play with it.
1) If you want column headers, that's what th tags are for... and they should go inside the thead tags you already have, like this:
var html = '<table><thead><tr><th>Timestamp</th><th>Variable 1</th><th>Variable 2</th><th>Variable 3</th><th>Variable 4</th></tr></thead><tbody>';
Read more about HTML tables here.
2) If you want an additional column, add in a value (a td - short for table data) before the loop that adds the randomize values
...
html += '<tr>';
html += '<td>' + new Date().getTime() + '</td>' <------ NEW CODE TO ADD ANOTHER VALUE
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
...
You can learn more about dates, both creating them and displaying them, here.
All said and done, your function would look like:
function htmlTable(d) {
var data = d;
var html = '<table><thead><tr><th>Timestamp</th><th>Variable 1</th><th>Variable 2</th><th>Variable 3</th><th>Variable 4</th></tr></thead><tbody>';
for (var i = 0, len = data.length; i < len; ++i) {
html += '<tr>';
html += '<td>' + new Date().getTime() + '</td>'
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
html += '<td>' + data[i][j] + '</td>';
}
html += "</tr>";
}
$(html).appendTo('#div1') ;
}

Putting image in table using innerHTML (Javascript / Html)

Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :
|item__ | price | category | category | category | category | picture |
|chicken| $20 | _______ |_ ______ | _______ | _______ | 1000.png|
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
if (j == 6) {
table += "<td>" + "<img src='CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
} else if {
table += "<td>" + array[i][j];
}
table += "<tr>";
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.
In the code below
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
table += "<td>" + array[i][j];
}
table += "<tr>";
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.
Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
I think there are several problems in your code that needs to be fixed :
You are not appending the td elements inside the tr but directly
inside the table, you need to move the line table += "<tr>";
before the nested loop.
And you are not specifying closing tags for <td> elements so when
you include the img tag it will mess up the layout.
Another thing just inverse the use of " and ' in your img tag
definition because HTML uses ".." to define attributes.
Here's how should be your code:
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
table += "<tr>";
for (var j = 0; j < array[i].length; j++) {
if (j == 6) {
table += "<td>" + '<img src="CSV_Photos/' + array[i][j] + '" style ="width:500px;height:300px"></td>';
} else if {
table += "<td>" + array[i][j] + "</td>";
}
}
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
Try:
var array = csvpls();
var table = "<table>";
for (var i = 0; i < array.length; i++) {
table += "<tr>";
for (var j = 0; j < array[i].length; j++) {
table += "<td>" + array[i][j];
}
table += "</tr>";
}
table += "</table>";
document.getElementById("Invtable").innerHTML = table;
If you wanted the image to be on the 2nd row, 3rd cell the condition should be:
if (i === 1 && j === 2) {...
If you want the whole 2nd row with the same image in each cell then it should be:
if (i === 1) {...
If you want a entire 3rd column to have the same image then it would be:
if (j === 2) {...
If it's a different image for every cell, then name each file by table coordinates like this...
img1-2.png
...then change the string that renders an image inside a cell as:
table += `<td><img src='http://imgh.us/img${i}-${j}.png' style ='width:50px;height:50px'></td>`
Or if I understand correctly, the array already has the filenames. If that's true, then the string should be...
table += `<td><img src='http://imgh.us/${array[i][j]}' style ='width:50px;height:50px'></td>`
... and the array would be something like this:
var array = [
['rt','AD','1000.png','uy','ii'],
['rt','AD','1001.png','uy','ii'],
['rt','AD','1002.png','uy','ii']
];
BTW, I had to do some changes to the code in order for it to work since it's only a partial code you provided, but the gist of it is the condition of course.
Also you'll notice the strange syntax of the strings, that's ES6 template literals or "strings on steroids".
Demo
var array = cvpls();
var table = ``;
for (var i = 0; i < array.length; i++) {
table += `<tr>`;
for (var j = 0; j < array[i].length; j++) {
if (i === 1 && j === 2) {
table += `<td><img src='http://imgh.us/statik.gif' style ='width:50px;height:50px'></td>`;
} else {
table += `<td>${array[i][j]}</td>`;
}
}
table += `</tr>`;
document.getElementById("Invtable").innerHTML = table;
}
function cvpls() {
return array = [
[4, 5, 6, 9, 2],
['img', 'img', 'img', 'img', 'img'],
['d', 'b', 'g', 'i', 'o']
];
}
td {
border: 1px solid black
}
<table id='Invtable'></table>

Dynamically assign unique id from var value in Javascript, jquery

In my program, I use javascript to generate a table which is then appended to the html document:
var html = "<table>";
for (var r = 0; r < rows; r++)
{
html += "<tr>";
for (var c = 0; c < cols; c++)
{
html += "<td class=\"covered\"><input type=\"image\" src=\"imageURL.com"/></td>";
}
html += "</tr>";
}
html += "</table>";
$(".gameboard").append(html);
I want each of the input elements to have a unique ID -- specifically a number. I was hoping to have a variable that is initialized to 1, which gets incremented each time a TD element is created. The value of this variable would be used as the input element ID. I haven't found any way to do this specifically. Thanks in advance!
Try this:
var html = "<table>";
var index=0;
for (var r = 0; r < rows; r++)
{
html += "<tr>";
for (var c = 0; c < cols; c++)
{
html += "<td class=\"covered\"><input id='img"+(index++)+"' type=\"image\" src=\"imageURL.com"/></td>";
}
html += "</tr>";
}
html += "</table>";
$(".gameboard").append(html);
Try to add a global variable let count and increment it in inner loop, like,
var html = "<table>";
var count=1;// use this variable in inner for loop and increment it by 1
for (var r = 0; r < rows; r++)
{
html += "<tr>";
for (var c = 0; c < cols; c++){
html += "<td class=\"covered\">\
<input id='"+(count++)+"' type=\"image\" src=\"imageURL.com\"/>\
</td>";
}
html += "</tr>";
}
html += "</table>";
$(".gameboard").append(html);
Try this code:
html += "<td id='td-" + c +"'class=\"covered\"><input value='td-" + c +"' type=\"image\" src=\"imageURL.com"/></td>";
use this
var ID= new Date().getTime();

Adding ending </tr> tags to an HTML strings within loop

I have an array of elements I would like to put into an HTML table:
var tags_arr = [1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19];
I can make an HTML table by simply placing beginning <tr> tags every 4th iteration:
var checks = "<table border=1>";
for (var c = 0; c < tags_arr.length; c++){
if (c%4 == 0){
checks += "<tr>";
}
checks += "<td>" + tags_arr[c] + "</td>";
}
checks += "</table>";
$("body").append(checks);
JSBIN
However this solution relies on the browser to inject the closing <\tr> tag when it "sees" the new opening tag. The browser also seems not to care that the last row has fewer <td> cells than the previous rows do.
It works, but is there a way to make expand this so as not to completely rely on the browser. I've tried using a regex to inject them into the string, but it seems like there should be a way to do so in the loop. Is it feasible? Or since it only has to work in modern browsers, can I just rely on Chrome and Firefox to do the cleanup for me?
EDIT:
hacky regex way:
checks = checks.replace(/(<tr>)/g, "</tr><tr>").replace(/<\/tr>/, "");
checks += "</tr></table>";
The HTML5 spec explicitly tells us that it's not necessary to close <tr> and <td> tags in the obvious scenarios:
No need to close a <td> before the next <td> or <tr> or table block section (<tbody>, <tfoot>), or the </table> closing tag.
No need to close a <tr> before the next <tr>, block section, or table close.
I seriously doubt you'll run into modern browsers that won't do the right thing here. I bet even IE6 will do it properly.
You can simply append the TR closing tag before appending the starting TR tag:
for (var c = 0; c < tags_arr.length; c++){
if (c%4 == 0){
if (c !== 0) checks +="</tr>";
checks += "<tr>";
}
checks += "<td>" + tags_arr[c] + "</td>";
}
checks += "</tr></table>";
PS: Take care of the edge cases.
EDIT:
A more elgant solution is to distribute the items in arrays before hand:
var distributed = [];
var tags_arr = [1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19];
while(tags_arr.length > 0) {
distributed.push(tags_arr.splice(0,4));
}
And then use some smart loops to create the html:
var html = distributed.reduce(function(html, item){
var td = item.reduce(function(html, item){
return html + '<td>' + item + '</td>';
}, '');
return html + '<tr>' + td + '</tr>';
}, '');
html = '<table border=1>' + html + '</table>';
for (var c = 0; c < tags_arr.length; c++){
if (c%4 == 0){
if (c > 0) {
checks += "</tr>";
}
checks += "<tr>";
}
checks += "<td>" + tags_arr[c] + "</td>";
}
if (c > 0) { // Don't add a closing tag if there were no rows at all
checks += "</tr>";
}
Just close the tr tag before opening one. If c == 0 no tag have been opened yet.
Don't forget to close the last tag after the for loop
var checks = "<table border=1>";
for (var c = 0; c < tags_arr.length; c++){
if (c%4 == 0){
if (c > 0)
checks += "</tr>"
checks += "<tr>";
}
checks += "<td>" + tags_arr[c] + "</td>";
}
if (tags_arr.length > 0)
checks += "</tr>"
var cell = 0, len = tags_arr.length;
for(var row = 0; cell < len; row++) {
checks += '<tr>';
for(var col = 0; col < 4 && cell < len; col++, cell++)
checks += '<td>' + tags_arr[cell] + '</td>';
checks += '</tr>';
}
The correct solution - no divisions, no exceptional cases, no extra memory.

create table with values using js

I want to create table using javascript and fill it with data. So I decided to use prompt method and loop while.
But when I try to load page I always get two error message in google chrome developer tools
Here is the code
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function onStart() {
var list = new Array();
var headers = new Array("Имя","Отчество","Фамилия","Дата рождения");
var i = -1;
while(true) {
var a = prompt("Имя","noname");
var b = prompt("Отчество","nomiddlename");
var c = prompt("Фамилия","nosurname");
var d = prompt("Дата рождения!",0);
if (confirm("Уверены что хотите добавить студента?")) {
i++;
list[i] = a + "-" + b + "-" + c + "-" + d;
}else{ break; };
}
tab = "<table>";
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
tab +="</table>";
document.write(tab);
};
</script>
</head>
<body onLoad = "onStart()">
</body>
What's the problem?
Your for loops seem to be mis-indented and not closed properly
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
Should be
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
}
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
Not directly related to your question, but you have a few other common javascript errors.
By not declaring variables with var, you are unintentionally creating global variables. While this probably isn't a huge issue on your page, but it is bad practice.
In addition, you should wrap your <th> tags you are appending inside of a <tr>, as the only "valid" element within a <table> is a <tr> (technically its tbody, thead, and tfoot, of which the only valid children is <tr>).
You're missing the closing } on your first loop:
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
}
I would go to guess he is trying to loop thru headers, followed by columns, then close the table. Not loop thru headers, and for each header add all rows. And, certainly not loop thru headers and for each header loop through all rows and close and write the table.
In your code onStart(){} method is not closed properly. Add one more "}" in front of the below code
</script>
</head>

Categories

Resources