Javascript html table not showing - javascript

I've been trying to total a list of die rolls (sum of pairs) in a table using javascript to avoid hard-coding 11 rows in my html page and accessing each row seperately later in the js file to add the values.
So I used a loop and document.writeln() to do this in a more compact way but the output doesn't show the table or anything.
document.writeln("<table border=\"1\"><thead><tr><th>Sum of Dice</th><th>Total Times Rolled</th></tr></thead><tbody>");
for (var i=0; i < 11; i++)
{
document.writeln("<tr><td>2</td><td></td></tr>");
}
document.writeln("</tbody></table>");
The rows shouldn't all start with 2, I only used that number as a test and the second tag in the for loop is for the totals that I already have in an array but my issue is with displaying the table.

Try this:
<script>
var code = "";
function write(){
code += "<table border=\"1\"><tr><th>Sum of Dice</th><th> Total Times Rolled</th></tr>";
for (var i = 0; i < 11; i++){
code += "<tr><td>2</td><td></td></tr>";
}
code += "</table>";
document.body.innerHTML = code;
}
</script>
And don`t forget to put this code to html:
<body onload="write()">
Here you have the result:

I think create table by writeln with whole bunch of HTML text string is generally not a good idea. I would recommend create table dom element via Javascript and append it to the wrapper element.
var headerContent = ['Sum of Dice', 'Total Times Rolled'];
var table = document.createElement('table'),
header = table.createTHead(),
row,
cell;
table.border = 1;
// construct header
row = header.insertRow(0);
for (var i = 0, len = headerContent.length; i < len; i++) {
cell = row.insertCell(i);
cell.innerHTML = headerContent[i];
}
// construct table content
for (var i = 0; i < 11; i++) {
row = table.insertRow(i + 1);
for (var j = 0, len = headerContent.length; j < len; j++) {
cell = row.insertCell(j);
cell.innerHTML = '2';
}
}
// add table element to the dom tree
var wrapper = document.getElementById('wrapper');
wrapper.appendChild(table);
See http://jsfiddle.net/LgyuE/

Related

double forEach to double for Loop

I'm creating an HTML table from a server-side array (google apps script; so tableArray is coming from there). I have two forEach functions which work. However, I'm attempting to use two for loops instead because I'd like to be able to add different classes to different <td>'s.
The output doesn't come out as expected (see #1 below). I can either get an array in one column (instead of each element of the array as a separate <td> or the arrays are repeated in each <td> (see #2 below).
What do I need to change in my for loops to get the expected output?
You can see the version that works HERE.
1 (works with forEach)
2 (does not work with for)
Index.html
function buildTable(tableArray) {
var table = document.getElementById('table');
var tableBody = document.createElement('tbody');
var tbodyID = tableBody.setAttribute('id', 'tbody');
for (var i = 0; i < tableArray.length; ++i) {
var column = tableArray[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
if (colA != "") {
var row = document.createElement('tr');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column));
row.appendChild(cell);
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
}
Instead of line cell.appendChild(document.createTextNode(column));
write cell.appendChild(document.createTextNode(column[j]));
You've forgotten to add index [j]
// Loop over rows
for (var i = 0; i < tableArr.length; i++) {
var row = tableArr[i];
// loop over columns
for( var j =0; j<row.length; j++){
//create each column and append to row
}
// append row to table body
}
// append table body to DOM
For performance reasons you want to write to the DOM only once and create the table in memory first.
Change
cell.appendChild(document.createTextNode(column));
to
cell.appendChild(document.createTextNode(column[i]));
This will make it loop through all of your column data properly instead of appending the same content of the whole array repeatedly.

Javascript Dynamically build HTML table with button cell

Trying to get my dynamic table to have a button in last column. Have had no luck. Any help much appreciated.
var removeRow=document.createElement("BUTTON");
//Add the data rows.
for (var i = 1; i < data.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < 3; j++) {
var cell = row.insertCell(-1);
if (j==0) {
cell.innerHTML = data[i].userId}
if (j==1) {
cell.innerHTML = data[i].id}
if (j==2) {
cell.innerHTML = data[i].title}
if (j==3) {
cell.appendChild(removeRow)// Not working when replace data[i].field with button variable.
}
}
In your loop, j never gets to 3 (it says j < 3 in your second for statement).
If you change that to j < 4 or j <= 3 it should work.
Apart from that, you are only creating one BUTTON element, which you will be appending to all rows. Every time you append it to a row, it will be removed from the previous row it was on, so you'll still be left with just one button.

Name each cell on each row from 1 to 9

the problemI want to make a sudoku solver and to do that I need to name each cell from 1 to 9 in every row. If you know another way to make this please tell me. Here's the code:
function crear (){
var table = document.getElementById("table");
// enter code here
for (var i = 1; i < 10; i++) {
var showfila = document.createElement("TR");
showfila.setAttribute("id", "myTr" + i);
document.getElementById("table").appendChild(showfila);
for (var a = 1; a < 10; a++) {
var input = document.createElement("INPUT");
input.setAttribute("id", "myInp" + a);
document.getElementById("myTr" + i).appendChild(input);
document.getElementById("myInp" + a).value=a;
}
}
}
I'm assuming the "name" you are talking about for each cell is the name property and also that these cells need to be created (based on your code) so you can do something like this:
EDIT
The name now includes the corresponding row and column. I also added comments so that if this is not what you are looking for, you can refer to them to edit your code correctly.
function createTable(){
var table = document.getElementById("table");
//Loop for rows
for (var i = 1; i < 10; i++) {
//Loop for columns
for (var j = 1; j < 10; j++) {
var cell = document.createElement("TR");
//var i would be the row and var j would be the column
cell.name=i+"-"+j;
table.appendChild(cell);
}
}
}

Create a title for each column on a table using a loop. JavaScript

I want the title for each column on a table to be'A','B','C' etc, I want to be able to change how many columns there are so I want to use a loop.
Code so far:
JavaScript:
<script>
document.getElementById('dtable').innerHTML = '';
var table = document.getElementById("dtable")
Rows = 4
for (var count = 0; count <= Rows; count++) {
var header = table.createTHead(0);
var row = header.insertRow(0);
var character = String.fromCharCode(65 + count);
var cell = row.insertCell(count);
cell.innerHTML =('<b>'+character+'</b>');
}
</script>
HTML:
<div id='div1'><table id="dtable"></table></div>
You were creating one row in the header for each column.
Moving the thead creation outside the loop fixed it.
document.getElementById('dtable').innerHTML = '';
var table = document.getElementById("dtable");
var header = table.createTHead(0);
var row = header.insertRow(0);
Rows = 4
for (var count = 0; count <= Rows; count++) {
var character = String.fromCharCode(65 + count);
var cell = row.insertCell(count);
cell.innerHTML =('<b>'+character+'</b>');
}
<div id='div1'><table id="dtable"></table></div>
You don't want to create a new row inside of the loop right? Move the head and row creation outside of the loop.
like:
<script>
document.getElementById('dtable').innerHTML = '';
var table = document.getElementById("dtable")
Rows = 4
var header = table.createTHead(0);
var row = header.insertRow(0);
for (var count = 0; count <= Rows; count++) {
var character = String.fromCharCode(65 + count);
var cell = row.insertCell(count);
cell.innerHTML =('<b>'+character+'</b>');
}
</script>
If you want it to look like a table with borders and such you'll have to add css styling but that should print a b c d e
Your problem is that you are creating the header and the row inside your for loop, which means that you will be creating a new row each time, which causes problems with row.insertCell. The first iteration works because you are inserting a cell in the 0th position, but the second iteration of the loop attempts to insert a cell in the 1st position, when a 0th position cell does not exist, hence why it throws an error. Try this and it should work for you:
document.getElementById('dtable').innerHTML = '';
var table = document.getElementById("dtable");
var Rows = 4;
var header = table.createTHead(0);
var row = header.insertRow(0);
for (var count = 0; count <= Rows; count++) {
var character = String.fromCharCode(65 + count);
var cell = row.insertCell(count);
cell.innerHTML =('<b>'+character+'</b>');
}
<div id='div1'><table id="dtable"></table></div>
#Dilly,
Use this fiddle... As many other answers for the post - you need to create a row once and columns as many times as you wish... so loop for columns not rows. Which also reminds me to tell you - Please don't use loop count variable name as "Row" that is point of confusion. You should name it - numOfColumns for example.
Thanks to the comment, I added this commentary.
https://jsfiddle.net/shemdani/xjpekb94/1/
document.getElementById('dtable').innerHTML = '';
var table = document.getElementById("dtable")
var row = table.insertRow(0);
Rows = 4
for (var count = 0; count < Rows; count++) {
var character = String.fromCharCode(65 + count);
var cell = row.insertCell(count);
cell.innerHTML =('<b>'+character+'</b>');
}

Put a line break in a for loop that is generating html content

I have a for loop that is generating some HTML content:
var boxes = "";
for (i = 0; i < 11; i ++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
}
document.getElementById("id").innerHTML = boxes;
I want to display 3 boxes in one row, then below them 2 boxes in one row, then 1, then 3 again, 2, and 1.
First i thought of using the if statement to check whether i > 2 to add a line break, but it will also add a line break after every box past the third one. Nothing comes to mind, and my basic knowledge of javascript tells me I'll have to make a loop for each row I want to make. Any advice?
I would use a different approch :
Use a array to store the number of item per row :
var array = [3, 2, 1, 3, 2];
Then, using two loops to iterate this
for(var i = 0; i < array.length; i++){
//Start the row
for(var j = 0; j < array[i]; ++j){
//create the item inline
}
//End the row
}
And you have a pretty system that will be dynamic if you load/update the array.
PS : not write javascript in a while, might be some syntax error
Edit :
To generate an id, this would be simple.
create a variable that will be used as a counter.
var counter = 0;
On each creating of an item, set the id like
var id = 'boxes_inline_' + counter++;
And add this value to the item you are generating.
Note : This is a small part of the algorithm I used to build a form generator. Of course the array contained much more values (properties). But this gave a really nice solution to build form depending on JSON
You can try something like this:
Idea
Keep an array of batch size
Loop over array and check if iterator is at par with position
If yes, update position and index to fetch next position
var boxes = "";
var intervals = [3, 2, 1];
var position = intervals[0];
var index = 0;
for (i = 0; i < 11; i++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
if ((position-1) === i) {
boxes += "<br/>";
index = (index + 1) % intervals.length;
position += intervals[index]
}
}
document.getElementById("content").innerHTML = boxes;
.box{
display: inline-block;
}
<div id="content"></div>
var boxes = "",
boxesInRow = 3,
count = 0;
for (i = 0; i < 11; i ++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
count++;
if(count === boxesInRow) {
boxes += "<br/>";
boxesInRow -= 1;
count = 0;
if (boxesInRow === 0) {
boxesInRow = 3;
}
}
}
document.getElementById("id").innerHTML = boxes;
var i;
var boxes = "";
for (i = 0; i < boxes.length; i++) {
boxes += "<div class=""><img src=""/></div>";
function displayboxes() {
"use strict";
for (i = 0; i < boxes.length; i++) {
out.appendChild(document.createTextNode(boxes[i] + "<br>"));
}
}
displayboxes(boxes);

Categories

Resources