Putting image in table using innerHTML (Javascript / Html) - javascript

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>

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

How to create a table in JS

I need to create a table in JS and show it in the page but it does not seem to work. I have two functions, the first one to actually create the table and the second one to order the elements in the table. I tried creating a simple div in html with id showlist but the table does not appear in the page. Please see the code below.
function myfunction() {
var array2 = [];
var list = "<table border ='1'>";
array2.sort(order);
list = list + "<tr>";
list = list + "<td colspan = '2'> TABLE </td>";
list = list + "</tr>";
list = list + "<tr>";
list = list + "<td> PRICE</td>";
list = list + "</tr>";
for (i = 0; i <= array2.length; i++) {
list = list + "<tr>";
list = list + "<td>" + array2[i].name + "</td>";
list = list + "<td>" + array2[i].price + "</td>";
list = list + "</tr>";
}
list = list + "</table>";
$("#showlist").html(list);
}
function order(n1, n2) {
if (n1.price > n2.price) {
return 1;
} else {
if (n1.price < n2.price) {
return -1;
} else {
return 0;
}
}
}
Your for loop <= runs from 0 to array2.length, it should be < - from 0 to array2.length-1.
for (i = 0; i < array2.length; i++) {
// ^_ Notice change here
...
}
Else, the last iteration would throw undefined errors.
Uncaught TypeError: Cannot read property 'name' of undefined
Fiddle Example

Cannot create a html table based on a string in Android

I want to create a table with html tags as strings, passing in the source code values from a 2d array.
I create a string and inside it I pass my variables
The desired format of the table data part is the following
<tr><td><td>CONTACT1 </td><td>125 </td><td>1 </td></td></tr>
<tr><td><td>CONTACT2 </td><td>126 </td><td>2 </td></td></tr>
<tr><td><td>CONTACT3 </td><td>127 </td><td>3 </td></td></tr>
<tr><td><td>CONTACT4 </td><td>128 </td><td>4 </td></td></tr>
But instead of this I get the following
<tr><td><td>CONTACT1 </td><td>125 </td><td>1 </td>
<td><td>CONTACT2 </td><td>126 </td><td>2 </td>
<td><td>CONTACT3 </td><td>127 </td><td>3 </td>
<td><td>CONTACT4 </td><td>128 </td><td>4 </td></td></tr>
I am trying with the following for loop
for (int i = 0; i < PlayerCount; i++)
{
for (int j = 0; j < 12; j++)
{
col = "<td>" +
contactsarray[i][j] +
" " +
"</td>";
mainsource = mainsource + col;
}
row="<tr><td>"+mainsource+"</td></tr>"+row;
}
How I am going to change table row and achieve the desired result by putting extra and for each contact?
No its not that, I need to reset the mainsource variable to mainsource=""
for (int i = 0; i < contactsarray.length; i++) //fixed for condition
{
for (int j = 0; j < contactsarray[i].length; j++) //fixed for condition
{
col = "<td>" +
contactsarray[i][j] +
" " +
"</td>";
mainsource = mainsource + col;
}
row="<tr>"+mainsource+"</tr>"+row;
mainsource="";
}
I think the problem is you are producing invalid html:
<tr><td><td>CONTACT1 </td><td>125 </td><td>1 </td></td></tr>
<tr><td><td>CONTACT2 </td><td>126 </td><td>2 </td></td></tr>
<tr><td><td>CONTACT3 </td><td>127 </td><td>3 </td></td></tr>
<tr><td><td>CONTACT4 </td><td>128 </td><td>4 </td></td></tr>
Columns (td) can not be wrapped with another column. Your for loop conditions could be improved as well to loop through the 2d array properly.
for (int i = 0; i < contactsarray.length; i++) //fixed for condition
{
var mainsource = ""; //fixed variable declaration
for (int j = 0; j < contactsarray[i].length; j++) //fixed for condition
{
var col = "<td>" + //fixed variable declaration
contactsarray[i][j] +
" " +
"</td>";
mainsource = mainsource + col;
}
row="<tr>"+mainsource+"</tr>"+row; //fixed so you are not wrapping columns with another column
}
Here is some good information on html tables and looping through a 2d array to help you understand:
http://www.w3schools.com/html/html_tables.asp
http://www.plus2net.com/javascript_tutorial/array-two-dimension.php

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

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