Dynamically assign unique id from var value in Javascript, jquery - javascript

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

Related

Clickable table

I created a simple function in JS that generates a table. Now I want to do this: when I click on some cell of the table, the page will alert the value what is inside the cell: variable b, as you can see in the code. I tried it, but I didn´t managed it. is inside the code. I also used Jquery.
The code: JS
function gen() {
var rowData = '';
for (var a = 0; a < 5; a++) {
rowData += '<tr>';
for (var i = 0; i < 3; i++) {
rowData += '<td>';
rowData += b;
rowData += '</td>';
b++;
}
rowData += "</tr>";
}
$('#myTableId2').append(rowData);
}
HTML:
<table id="myTableId2"> </table>
<button onclick="gen()">Generate</button>
rowData += '<td onclick="alert(this.innerHTML)">';
I see you're using jQuery. You can attach a click() event to each <td> element as I do below.
Note that since b is undefined in your example, I took the liberty of giving it a random value for illustrative purposes.
function gen() {
let b = Math.floor(Math.random() * 1000) + 1; //generate random value
var rowData = '';
for (var a = 0; a < 5; a++) {
rowData += '<tr>';
for (var i = 0; i < 3; i++) {
rowData += '<td>';
rowData += b;
rowData += '</td>';
b++;
}
rowData += "</tr>";
}
$('#myTableId2').append(rowData);
//attach the click event using jQuery
$("td").click(function(){alert(this.innerText)});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId2"> </table>
<button onclick="gen()">Generate</button>

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 Creating HTML table from JS array with jQuery

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>

JavaScript Create Calendar Table in DOM

I have created a table with 6 rows and 5 cols. The table is created for each month having presumably different number of days. I would like each col to display a date from 1-30 or 1-31 (depending on the month).
This is what I have so far:
function daysOfMonth(){
var table= " ";
var rows= 3;
var cols=6;
var number= 31;
for(var r=0; r<rows; r++){
table+= "<tr>";
for(var c=0; c<=cols; c++){
table+= "<td>" + c +"</td>"
// each col should display number for(var i=0l i<=number; i++)
}
table+= "</tr>"
}
document.write('<table>' + table +"</table>")
};// func end
Here is a codepen http://codepen.io/cb42/pen/KNJWrd
As i've see your code get two little bugs, solved in my simple example.
By this poin could you try to make it better. But i expect it helps you to understand how to make a calendar.
https://jsfiddle.net/cyzbhkjs/
function daysOfMonth(){
var _table= "<p>jol</p> ";
var rows= 5;
var cols=6;
var c= 1;
var daysMonth =31;
for(var r=0; r<rows; r++){
_table+= "<tr>";
for(var i=0; i<=cols; i++){
if(c<=daysMonth){
_table+= "<td>" + c +"</td>";
}else{
break;
}
c++;
// each col should display number at i
}
_table+= "</tr>";
}
document.getElementById('calendar').innerHTML = '<table>hola' + _table +'</table>';
};
daysOfMonth();
Thanks

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