Function to create a table inside my div - javascript

I made a function create_table(...) that is supposed to add the HTML for a table to the end of the inner HTML of a given element. What should be happening the following code is that when I click the Show Tree button, a table should be created inside the third div. For some reason I'm getting the error Property 'getElementById' of object #<HTMLDocument> is not a function. Any help greatly appreciated.
<html>
<head>
<style type="text/css">
div
{
border: 1px dashed;
}
table
{
border: 1px dashed red;
}
#instructdiv
{
}
#inputdiv
{
}
#outputdiv
{
}
</style>
<script type="text/javascript">
function create_table(rows, columns, elementId)
{
/* Adds at the end of the HTML for a container with
elementId the HTML for a table with a specified
number of rows and columns.
*/
var newHTML = document.getElementById(elementId).innerHTML;
newHTML += "<table>";
for (var i = 0; i < rows; ++i)
{
newHTML += "<tr>";
for (var j = 0; j < columns; ++j)
newHTML += "<td>j</td>";
newHTML += "</tr>";
}
newHTML += "</table>";
document.getElementById = newHTML;
}
function make_tree()
{
/* To do: Determine number of rows and columns by user input.
For testing now, just make the table an arbitrary size.
*/
create_table(4,50, "outputdiv");
}
</script>
</head>
<body>
<div id="instructdiv">
<p>In the text field below, enter integers in the range 0 through 127 separated by spaces,
then push Show Tree.</p>
</div>
<div id="inputdiv">
<textarea id="inputText" scrolling="yes"></textarea>
<p></p>
<button onclick="make_tree()">Show Tree</button>
</div>
<div id="outputdiv">
<!-- binary tree table is housed here -->
</div>
</body>
</html>

Change your code to this. You shouldn´t assign document.getElementById ( which is a function ) to an string, because de the function being unusable.
function create_table(rows, columns, elementId)
{
/* Adds at the end of the HTML for a container with
elementId the HTML for a table with a specified
number of rows and columns.
*/
var element = document.getElementById(elementId);
var newHTML = element.innerHTML;
newHTML += "<table>";
for (var i = 0; i < rows; ++i)
{
newHTML += "<tr>";
for (var j = 0; j < columns; ++j)
newHTML += "<td>j</td>";
newHTML += "</tr>";
}
newHTML += "</table>";
element.innerHTML = newHTML;
}
function make_tree()
{
/* To do: Determine number of rows and columns by user input.
For testing now, just make the table an arbitrary size.
*/
create_table(4,50, "outputdiv");
}

Related

Create table of specified column and rows in Jquery

I am new to jQuery, I want to create table with specific number of rows and columns in jQuery.
Here is what I tried this creates table with specific number of rows but it doesn't create table of specific number of columns
function constructTable () {
let table = $('<table>').first().prepend('<caption><b> Borrow </b></caption>');
let row;
let cell1;
let cell2;
table.attr({"id":"burrow"});
for(i=0; i < 3; i++) {
row = $('<tr>');
table.append(row);
}
for ( i = 0 ; i < 4; i++ ) {
cell1 = $('<td>').text('cell ' + i);
row.append(cell1);
}
$("#borrowLicensediv").append(table);
document.getElementById('borrowLicensediv').style.display = '';
}
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body onload="constructTable ()" style="background: white;">
<div id="borrowLicensediv" style="display: none; margin-top:10px; margin-bottom:25px; margin-left:20px; margin-right:37px;"></div>
</body>
</html>
Before you append rows to the table these must first have cells otherwise you're going to have empty rows in your table with no columns. Leaving jQuery aside for a moment, the general problem is:
Build a row
Append it to the table
Repeat 1 and 2 for all rows to add
Step (1) implies that you first create the cells you want in the row and add them to the row. This means you're going to have nested loops (whereas in your example they're inline).
You need something more like
for(i=0; i < 3; i++) {
var row = "<tr>";
for ( j = 0 ; j < 4; j++ ) {
var value = "cell " + i + "," + j;
var td = "<td>" + value + "</td>";
row += td;
}
row += "</tr>";
table.append(row);
}
You are adding the TDs to the last Row because your cell loop is outside of the Row loop. We need to move the loop inside and fix the iterator variable, like this:
for(var r=0; r < 3; r++) {
row = $('<tr>');
for ( var c = 0 ; c < 4; c++ ) {
cell = $('<td>').text('cell ' + r+c);
row.append(cell);
}
table.append(row);
}

Generating an html table using javascript

My homework assignment is to generate a checkered html table (aka a chess board) using javascript. I have to use the getElementById and innerHTML properties to do it. I am supposed to generate html strings and add them to the document.
This is what I've written, when i open the page it is empty though, it isn't generating anything at all.
html/script:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="gameTableStyle.css">
<script>
function showTable() {
var tableDiv = document.getElementById("tableDiv");
tableDiv.innerHTML = genTable();
}
function genTable() {
var html = "";
var i = 0;
var j = 0;
var tClass = "white";
html += "<table>";
for (i = 0; i < 8; i++) {
html += "<tr>";
for (j = 0; j < 8; j++) {
if (i % 2 = 0) {
tClass = "black";
}
else {
tClass = "white";
}
html += "<td>" + "</td>;
}
html += "</tr>";
}
html += "</table>"
return html;
}
</script>
</head>
<body onload="showTable()">
<div id="tableDiv">
</div>
</body>
</html>
css:
.black {
color: black;
}
.white {
color: white;
}
This is my first class on html/javascript so I'm sure there are fancier ways to do this but we are specifically supposed to do it by generating the strings and inserting them in the document. I don't know what I'm doing wrong.

jQuery, adding multiple table rows is not working correctly

The idea is to build a function that takes an input and uses that to build a grid. I'm trying to establish the grid functionality first, and I'm having a peculiar error. I searched for a few hours, but the answers all tell me that a simple "append" should be working.
The specific error that I am getting:
When I load up the webpage, it is only adding one table row to the tbody, and only one table data to that table row. The idea is instead to create a grid of 16 x 16, with 16 rows and 16 data. Console logs show that the loops are all working correctly.
The html is just a basic file that imports the javascript correctly (All tested) with a simple:
div class="container" /div
Code:
$(document).ready(function(){
$(".container").html("");
/*this function makes a table of size numRow and
num data. it then gives each data element
*/
//blank rows to insert
var blankResults = $("<table>");
var result = blankResults;
var row = $("<tr/>");
var data = $("<td/>");
function makeTable(num)
{
result = blankResults;
//create num rows
for (var i = 0; i < num; i++)
{
//for each row
//add data num times
for (var j = 0; j < num; j++)
{
console.log(j);
row.append(data);
}
//append row
console.log(i);
result.append(row);
}
}
//starting area
makeTable(16);
$(".container").append(result);
//Start with 16 by 16 of square divs -
//put inside a container div
});
Try this code.
$(document).ready(function(){
$(".container").html("");
/*this function makes a table of size numRow and
num data. it then gives each data element
*/
function makeTable(num)
{
var output = '<table>';
//create num rows
for (var i = 0; i < num; i++)
{
//for each row
output+= '<tr>'
for (var j = 0; j < num; j++)
{
output += '<td></td>';
}
output += '</tr>';
}
output += '</table>';
return output;
}
//starting area
var result = makeTable(16);
$(".container").append(result);
//Start with 16 by 16 of square divs -
//put inside a container div
});
You are appending to the same variables all the time...row and 'data`. you should not do that.
As you can see from the code below, you need to create the var row = $("<tr>"); on each loop, to reference it when you append the <td> (table cell) to that newly created row.
Modifed to use only one loop:
$(document).ready(function(){
function makeTable(num) {
var table = $("<table>"), row;
for (var i = 0; i < num; i++){
row = $("<tr>");
table.append(row);
row.append(Array(num + 1).join("<td></td>"));
}
return table;
}
$(".container").html(makeTable(16));
});
DEMO PLAYGROUND
Of course, this is not a good way generating a table. running jQuery function on each loop is slow and bad practice. You should generate a big string which will represent your DOM structure and then append that string where needed and jQuery will make a DOM node out of it.
I made up my own html for this but it should be as simple as using two nested for loops grabbing values the size input. Here's what I came up with:
$("#tableMaker").click(function () {
$('.container').html("");
$('.container').append("<table></table>");
for (var i = 0; i < $('#size').val(); i++) {
$('table').append("<tr></tr>");
for (var j = 0; j < $('#size').val(); j++) {
$('tr:last').append("<td>Column " + (j+1) + ", Row " + (i+1) + "</td>");
}
}
})
td {
border: black solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="size" placeholder="Size" />
<button id="tableMaker" type="button">Generate Table</button>
<br />
<div class="container">
<div />

Populate table from array using JQuery

I have an array of 16 elements that I want to fill a table. I want it to have 2 rows with 8 cells in each row which is filled with the array. My problem is that when the table is populated, the table populates all elements into one row. I have not had much experience with JQuery and I want to try to get this to work. Any help is appreciated! Here is my code:
//**********Javascript & JQuery**********
var array = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8];
var count = 0;
var totalCells = 8;
function writeTable() {
var $table = $('#summaryOfResults');
//Array always includes enough elements to fill an entire row, which is 8 cells. Outer loop determines how many rows to make.
//Inner loop determines the elements to print in the cells for that row.
for (var i = 0; i < array.length / 8; i++) {
$table.find('#body').append('<tr>');
for (var j = 0; j < totalCells; j++) {
$table.append('<td>' + array[count] + '</td>');
count++;
}
$table.append('</tr>');
}
}
//**********HTML**********
<html>
<head>
</head>
<body>
<div id="resultsTable">
<table id='summaryOfResults' border='1'>
<tbody id="body">
<tr>
<th>#</th>
<th>n<sub>i</sub></th>
<th>n<sub>f</sub></th>
<th>E<sub>i</sub> (J)</th>
<th>E<sub>f</sub> (J)</th>
<th>ΔE (J)</th>
<th>ΔE (kJ/mol)</th>
<th>λ (nm)</th>
</tr>
</tbody>
</table>
</div>
<div id="tableButtons">
<button id='copyButton' onclick=''>Copy Table</button>
<button id='clear' onclick='clearTable();'>Clear Table</button>
<button id='write' onclick='writeTable();'>Write Table</button>
</div>
</body>
</html>
First, you have to reset count on every click.
Next, you have to specify where exactly the <td> elements have to be appended to. As for now, you're appending them directly to the <table> :
// your declaration of the table element:
var $table = $('#summaryOfResults');
// ...
// then in nested loop, you're appending the cells directly to the table:
$table.append('<td>' + array[count] + '</td>');
The last thing - .append('</tr>') is not a proper way to create an element object, it should be '<tr/>' , or '<tr></tr>'.
This should be what you're looking for:
function writeTable() {
// cache <tbody> element:
var tbody = $('#body');
for (var i = 0; i < array.length / 8; i++) {
// create an <tr> element, append it to the <tbody> and cache it as a variable:
var tr = $('<tr/>').appendTo(tbody);
for (var j = 0; j < totalCells; j++) {
// append <td> elements to previously created <tr> element:
tr.append('<td>' + array[count] + '</td>');
count++;
}
}
// reset the count:
count = 0;
}
JSFiddle
Alternatively, make a HTML string and append it to the table outside of the loop:
function writeTable() {
// declare html variable (a string holder):
var html = '';
for (var i = 0; i < array.length / 8; i++) {
// add opening <tr> tag to the string:
html += '<tr>';
for (var j = 0; j < totalCells; j++) {
// add <td> elements to the string:
html += '<td>' + array[count] + '</td>';
count++;
}
// add closing </tr> tag to the string:
html += '</tr>';
}
//append created html to the table body:
$('#body').append(html);
// reset the count:
count = 0;
}
JSFiddle

How to create a table using a loop?

The individual table rows are giving me a problem. I have created what I want using divs but I need to use a table instead of divs. My table has 220 cells, 10 rows, and 22 columns. Each cell has to have the value of i inside the innerHTML. Here is similar to what i want using Divs ( although the cell height and width does not have to be set ):
<!DOCTYPE html>
<html>
<head>
<style>
#container{
width:682px; height:310px;
background-color:#555; font-size:85%;
}
.cell {
width:30px; height:30px;
background-color:#333; color:#ccc;
float:left; margin-right:1px;
margin-bottom:1px;
}
</style>
</head>
<body>
<div id="container">
<script>
for( var i = 1; i <= 220; i++ ){
document.getElementById( 'container' ).innerHTML +=
'<div class="cell">' + i + '</div>'
}
</script>
</div>
</body>
</html>
http://jsfiddle.net/8r6619wL/
This is my starting attempt using a table:
<script>
for( var i = 0; i <= 10; i++ )
{
document.getElementById( 'table' ).innerHTML +=
'<tr id = "row' + i + '"><td>...</td></tr>';
}
</script>
But that code somehow dynamically creates a bunch of tbody elements. Thanks for help as I newb
You can do this with nested loops - one to add cells to each row and one to add rows to the table. JSFiddle
var table = document.createElement('table'), tr, td, row, cell;
for (row = 0; row < 10; row++) {
tr = document.createElement('tr');
for (cell = 0; cell < 22; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = row * 22 + cell + 1;
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
Alternatively, you can create an empty row of 22 cells, clone it 10 times, and then add the numbers to the cells.
var table = document.createElement('table'),
tr = document.createElement('tr'),
cells, i;
for (i = 0; i < 22; i++) { // Create an empty row
tr.appendChild(document.createElement('td'));
}
for (i = 0; i < 10; i++) { // Add 10 copies of it to the table
table.appendChild(tr.cloneNode(true));
}
cells = table.getElementsByTagName('td'); // get all of the cells
for (i = 0; i < 220; i++) { // number them
cells[i].innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
And a third option: add the cells in a single loop, making a new row every 22 cells.
var table = document.createElement('table'), tr, td, i;
for (i = 0; i < 220; i++) {
if (i % 22 == 0) { // every 22nd cell (including the first)
tr = table.appendChild(document.createElement('tr')); // add a new row
}
td = tr.appendChild(document.createElement('td'));
td.innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
Edit - how I would do this nowadays (2021)... with a helper function of some kind to build dom elements, and using map.
function make(tag, content) {
const el = document.createElement(tag);
content.forEach(c => el.appendChild(c));
return el;
}
document.getElementById("container").appendChild(make(
"table", [...Array(10).keys()].map(row => make(
"tr", [...Array(22).keys()].map(column => make(
"td", [document.createTextNode(row * 22 + column + 1)]
))
))
));
There are a lot of ways to do this, but one I've found to be helpful is to create a fragment then append everything into it. It's fast and limits DOM re-paints/re-flows from a loop.
Take a look at this jsbin example.
Here's the modified code:
function newNode(node, text, styles) {
node.innerHTML = text;
node.className = styles;
return node;
}
var fragment = document.createDocumentFragment(),
container = document.getElementById("container");
for(var i = 1; i <= 10; i++) {
var tr = document.createElement("tr");
var td = newNode(document.createElement("td"), i, "cell");
tr.appendChild(td);
fragment.appendChild(tr);
}
container.appendChild(fragment);
You can modify whatever you want inside the loop, but this should get you started.
That's because the DOM magically wraps a <tbody> element around stray table rows in your table, as it is designed to do. Fortunately, you can rewrite your loop in a way that will add all of those table rows at once, rather than one at a time.
The simplest solution to achieve this would be to store a string variable, and concatenate your rows onto that. Then, after you've concatenated your rows together into one string, you can set the innerHTML of your table element to that one string like so:
<script>
(function() {
var rows = '';
for( var i = 0; i <= 10; i++ )
{
rows += '<tr id = "row' + i + '"><td>...</td></tr>';
}
document.getElementById( 'table' ).innerHTML = rows;
}());
</script>
Here's a JSFiddle that demonstrates what I've just written. If you inspect the HTML using your browser's developer tools, you'll notice that one (and only one) tbody wraps around all of your table rows.
Also, if you're wondering, the odd-looking function which wraps around that code is simply a fancy way of keeping the variables you've created from becoming global (because they don't need to be). See this blog post for more details on how that works.
please check this out.
This is a very simple way to create a table using js and HTML
<body>
<table cellspacing="5" >
<thead>
<tr>
<td>Particulate count</td>
<td>Temperature</td>
<td>Humidity</td>
</tr>
</thead>
<tbody id="xxx">
</tbody>
</table>
<script>
for (var a=0; a < 2; a++) {
var table1 = document.getElementById('xxx');
var rowrow = document.createElement('tr');
for ( i=0; i <1; i++) {
var cell1 = document.createElement('td');
var text1 = document.createTextNode('test1'+a);
var cell2 = document.createElement('td');
var text2 = document.createTextNode('test2'+a);
var cell3 = document.createElement('td');
var text3 = document.createTextNode('test3'+a);
cell1.appendChild(text1);
rowrow.appendChild(cell1);
cell2.appendChild(text2);
rowrow.appendChild(cell2);
cell3.appendChild(text3);
rowrow.appendChild(cell3);
}
table1.appendChild(rowrow);
}
</script>
</body>
</html>

Categories

Resources