What are the javascript parts in this for loop? - javascript

Can someone explain to me the parts of the for loops?
for (let i = 0; i < height; i++) {
grid += '<tr class="row-' + i + '">';
// loop for each cell
for (let j = 0; j < width; j++) {
grid += '<td class="cell" id="row-' + i + '_cell-' + j + '"></td>';
}
grid += '</tr>';
}
Unfortunately, I don't get the grid parts. How can I write it in a different way?

The grid variable is practically the content of the table. On each grid line, a new HTML element is generated (except the last one).
For i iterations, a new row is added with a class name equivalent to the iteration index. Considering how rows are indexed vertically on a table, height is used as a metric for the y axis.
Similarly, j iterations add a new cell into the current 'i' row. Considering how a cell is combination of a row and column on a table, width is used as a metric for the x axis.
After the second (j) loop is finished, the closing tag </tr>is added in order to close the current iterated row.

In your code, the grid is simply making height number of rows and width number of rows. The grid will store this HTML code and then it must probably be replacing it somewhere using Html DOM manipulation.
What are the javascript parts in this for loop?
The loop is part of javascript, the height, width, grid variables are part of javascript. Even the HTML code you are storing is part of javascript since it is being stored in grid which is just another JS variable.
You can refer the below code to see what the code is really doing -
<!DOCTYPE html>
<html>
<body>
<p>This example demonstrates the <b>making a table using JS</b> method.</p>
<p id="demo"></p>
<script>
//var is used to store the HTML code, height and width store the number of rows and columns of table
var grid = "<table>",
height = 5,
width = 5;
for (let i = 0; i < height; i++) {
grid += '<tr class="row-' + i + '">';
// loop for each cell
for (let j = 0; j < width; j++) {
grid += '<td class="cell" id="row-' + i + '_cell-' + j + '"> (' + i + ' , ' + j + ' )    </td>';
}
grid += '</tr>';
}
grid += "</table>";
// Below we are just replacing the HTML in p with HTML that we filled in grid
var x = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = grid;
</script>
</body>
</html>

The grid part is just a variable name the programmer chose. It is a simple nestes for loop that will produce html that will look like this (for a 1x1 input)
With the variables i and j representing the index of their loop.

Related

generating a table onto html with .innerHTML from 2d arraylist javascript

I am trying to innerHTML the table with a 2d arraylist, but it seems like i am only getting the table as 1 column, all cells stacked on top of one another.
Could you guys see what I did to do this, and see how to resolve this? Thank you
for(var i = 0; i < transposedList.length; i++) {
tablehere.innerHTML += '<tr>';
for(var j = 0; j < transposedList[i].length; j++) {
tablehere.innerHTML += '<td>' + transposedList[i][j] + '</td>';
}tablehere.innerHTML += '</tr>';
}

ID to many elements elements

I have maybe weird question, but it is very important to me to solve this.
I have table wich is not with stable amount of rows and columns, so i put the += operator to create cells, rows and etc. Now i need to identify every cell, but i don't understand how i can do it in this situation.
function drawBoard(board) {
var t="";
t="<table border: 2px >";
var x,y;
for(x=0; x<board.length; x++){
t+="<tr>";
for(y=0; y<board.length; y++){
t+="<td class='tablecell' onclick=''>X</td>"
}
t+="</tr>";
}
t+="</table>";
}
By identify a cell I'm assuming you would like to reference them later in different part of the code.
You could achieve it by giving your rows and cells classes and/or ids.
For a row, for example:
t += '<tr id="tr-' + x + '">';
for a cell
t += '<td class="tablecell tr-' + x + ' col-' + y + '" onclick="" id="td-' + x + '-' + y + '">X</td>'
Then rows can be referenced by #tr-x and cells #tr-x > td, and all specific columnd .col-y
As Matheus Avellar mentioned, added id to a cell as well in case you want to reference a particular cell on a grid using #td-x-y
You are able to use:
const cells = document.getElementsByClassName('tablecell')
Or you can collect every cell on the stage of creation, for example:
const cells = [];
for (let i = 0; i < board.length){
for (let j = 0; j < board.length){
const cell = document.createElement('td');
cells.push(cell);
}
}
You can set the id of each one equal to your 'y' variable.
Something like:
function drawBoard(board) {
var t = "";
t = "<table border: 2px >";
var x, y;
for (x = 0; x < board.length; x++) {
t += "<tr>";
for (y = 0; y < board.length; y++) {
t += `<td id="table-${y}" class='tablecell' onclick=''>X</td>`
}
t += "</tr>";
}
t += "</table>";
}
Using a bit of ES6 template literals, you can set tie your ID to your 'Y' variable since it's an incrementing number.

Connect single image to single cell in a table with Javascript

I'm quite new both to programming and to this community, I'll try to be as clear as possible. I need to create an HTML table 16x16 with a button in every cell that displays a different image - a smiley - per cell, without ever showing the same smiley for different cells. I'm a bit stuck and I would also appreciate a hint, just to try and move on on my own. Thanks! Here is my code that creates the table and displays the image:
function displayImage(){
var num = Math.floor(Math.random() * 256);
document.canvas.src = '../../output/'+ imagesArray[num]+ '.png';
document.getElementById("YourImage").style.visibility = "visible";
}
for(var r = 0; r < rows;r++)
{
table += '<tr>';
for(var c= 0; c< cols;c++)
{
table += '<td style="width:50px" id="(i++)">' + '<button type="button" onclick="displayImage()">' +
"show me" + '</button>' + '</td>';
}
table += '</tr>';
}
document.write('<table id="grid" border="1">' + table + '</table>');
(ImagesArray is not shown for readability but it simply collects all 256 binary combinations).
The problem with this is that each time I click on a button it displays a random image and if I click again on the same button it shows another one, while I'd like it to show me always the same image for the same button.
NOTE: I cannot delete the button afterwards or similar tricks, as the player (it's an oTree experiment) needs to be able to go back to a smiley he saw any time.
Thanks a lot for your help!
I would change the point where the random number is generated and advance it from the display function to the initialization of the table.
Create an array with the numbers from 0 to 255. While looping through rows and columns to create the table, pick one random number from that array and assign it to the button's id attribute. Be sure to remove this number from the array, so it can't be used again for the following buttons. This way every of the 256 numbers will be used, but in random order. When a user clicks a button, with displayImage(this.id) the button's id is used as a parameter to call displayImage(). Thus always the same number of the button will be used the fetch the according image.
The code:
// call displayImage() with parameter
function displayImage(num){
document.canvas.src = '../../output/'+ imagesArray[num]+ '.png';
document.getElementById("YourImage").style.visibility = "visible";
}
// create array 'nums' with numbers from 0 to 255 (= rows * cols)
var nums = [];
for (var i = 0; i < (rows * cols); i++) {
nums.push(i);
};
for(var r = 0; r < rows; r++)
{
table += '<tr>';
for(var c = 0; c < cols; c++)
{
// get random index in array 'nums'
var random = Math.floor(Math.random() * nums.length);
// assign an id to the button with a random number from 'nums' and use this id in displayImage()
table += '<td style="width:50px" id="(i++)">' + '<button id="' + nums[random] + '" type="button" onclick="displayImage(this.id)">' +
"show me" + '</button>' + '</td>';
// remove the already used random number from 'nums'
nums.splice(random, 1);
}
table += '</tr>';
}
document.write('<table id="grid" border="1">' + table + '</table>');
This way you will have the same image connected to every button. It's randomized while creating the table, so the order is different every time you load the page.
I assume you are using HTML5 because only then it is permitted that id attributes consists only of digits.
Note: I don't know what exactly you want to achieve with id="(i++)" when creating the <td> element. The way you do it just names every id with the string (i++) which contradicts the idea that ids should be unique. If you want to name the ids ascending from for example td-0 to td-255 you should change the line to:
table += '<td style="width:50px" id="td-' + (r * rows + c) + '">' + '<button id="' + nums[random] + '" type="button" onclick="displayImage(this.id)">' + "show me" + '</button>' + '</td>';
You can't just use the numbers without adding something like td-, because the buttons already have pure numbers as id.
try this:
var rows = 16, cols = 16;
var table = '';
function shuffle(array) { // shuffle (randomize) array elements
var i = array.length, j, x;
while (i) {
j = Math.random() * i-- | 0;
x = array[i];
array[i] = array[j];
array[j] = x;
}
}
var rNums = new Array(rows * cols);
for (var i = 0; i < rows * cols; i++) {
rNums[i] = i;
}
shuffle(rNums);
function displayImage(num) {
//var num = Math.floor(Math.random() * 256);
document.canvas.src = '../../output/'+ imagesArray[num]+ '.png';
//document.getElementById("canvas").innerHTML = num;
document.getElementById("YourImage").style.visibility = "visible";
}
var i = 0;
for (var r = 0; r < rows; r++) {
table += '<tr>';
for (var c = 0; c < cols; c++) {
table += '<td style="width:50px" id="' + i + '"><button type="button" onclick="displayImage(' + rNums[i] + ')">show me</button></td>';
i++; //go to next element of rNums array
}
table += '</tr>';
}
document.write('<table id="grid" border="1">' + table + '</table>');

How to calculate how many rows and columns are needed

I want to produce a table with Javascript. I want to give it a number and that's how many cells are created. There are always to be 3 columns however (3 pictures per row)
Could someone help me out with this? I think I need to use the modulus operator but I am unsure of how to use it correctly.
I do not want any extra cells. I can calculate the rows without issue but I don't want extra cells for those rows if that makes sense. So once the cells have been made that row ends even if it's 1 or 2 cells short.
I have this at the moment:
rows = ?? //Not sure how to calculate this
columns = 3;
str = "";
str += '<table border="1" cellspacing="1" cellpadding="5">';
for(i = 0; i < rows; i++){
str += '<tr>';
for (j = 0; j < columns; j++){
str += '<td>' + (i + j) + '</td>';
}
str += '</tr>';
}
str += '</table>';
Say if u have number of pictures as numPictures:-
Then
var numRows = Math.ceil(numPictures/3);
I hope the following code that what you want.
var numOfPics = 100; // Number of Pictures
var columns = 3, rows = Math.ceil(numOfPics / columns), content = "", count = 1;
content = "<table border='1' cellspacing='1' cellpadding='5'>";
for (r = 0; r < rows; r++) {
content += "<tr>";
for (c = 0; c < columns; c++) {
content += "<td>" + count + "</td>";
if (count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
count++;
}
content += "</tr>";
}
content += "</table>";
document.body.innerHTML = content; // insert `content` value into body of page
You know how many cells there are. So you divide the number of cells by the number of columns to get the number of rows. Math.ceil() rounds up in case there are not the exact amount of cells to fill a row.
rows = Math.ceil(total_num_cells / 3);

How would I fill an empty cell in a HTML table with another word using JavaScript?

I'm trying to make a table that has 3 cells to a row, and into those three cells, I have a string that I get from a textbox from a HTML form that I created an array from. I'm using JavaScript to do this, and I have it to where I have each word in their own cell, but if there is an empty cell, it won't create a cell. How can I fill that empty cell with another word like "empty".
This is what I have so far.
arrays=tx_val.split(' ');
table="< table border='1' bgcolor=gray>"
for(x=0;x< arrays.length-2;x=x+3)
{
if(x<arrays.length-2)
{
table=table+"< tr>< td>"+arrays[x]+"< /td> <td>"+arrays[x+1]+
"< /td>< td>"+arrays[x+2]+"</td><td>";
}
else
{
table=table+"< /tr>< /table>"
}
}
|| 'empty'
as in
(arrays[x] || 'empty')
or
var empty = '--empty--';
if(x) table += "<tr><td>" + (arrays[x] || empty) + "</td> " + (arrays[x+1] || empty) + "</td><td>" + (arrays[x+2] || empty) + ""
There are errors in your logic that might be causing you problems:
for(x=0;x< arrays.length-2;x=x+3)
{
if(x<arrays.length-2)
Based on the for loop, the if statement will always evaluate to true. As such, for every iteration, you are adding a table row without an ending tr element and you are adding a table cell without an ending td element. The result will be ill-formed HTML that might not be rendering as you desire, even if you get some 'empty' value put in a cell.
Try this:
arrays = tx_val.split( ' ' );
table = "< table border='1' bgcolor=gray>";
currItem = 0;
for( x = 0; x < Math.ceil( arrays.length / 3 ); x = x + 1 )
{
table = table + "<tr>";
for( y = 0; y < 3; y = y + 1 )
{
if( arrays[currItem] == "" )
{
displayItem = "";
}
else
{
displayItem = arrays[currItem];
}
table = table + "<td>" + displayItem + "</td>";
currItem = currItem + 1;
}
table = table + "</tr>";
}
Basically, I changed the loops to form the table code per row first, then per column.
The outer for loop is the one responsible for adding code for each row. The Math.ceil( arrays.length / 3 ) formula determines the number of rows the table should have depending on the number of values in the array. The inner for loop creates 3 cells for each row.
If you want to change the dimensions of the table want to create you can just change the divisor in the Math.ceil function in the outer loop as well as the number used in the condition in the inner loop ( y < 3 ).

Categories

Resources