Create table of specified column and rows in Jquery - javascript

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

Related

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>

Show total no. rows for in HTML <span>

I need your help in displaying the total number of rows for the available tables in the appropriate span. There are 3 tables and I want the below code to show the total no. of rows in the first table in span1 & the total no. of rows for the second table in span2.
The JavaScript is:
function count() {
var tables = document.getElementsByClassName("tablesorter");
var rows;
var span = Array();
for (var i = 0; i < tables.length; i++) {
rows = tables[i].rows.length-1;
alert(rows);
alert(span[i]);
span[i].innerHTML = rows;
}
}
However, span[i] is not picking up the value and print it in the HTML span.
The HTML code is:
<body>
<span id="span1"></span>
<span id="span2"></span>
<span id="span3"></span>
</body>
I am looking forward your assistant and help.
Use this function instead:
function count() {
var tables = document.getElementsByClassName("tablesorter");
var rows;
for (var i = 0; i < tables.length; i++) {
rows = tables[i].rows.length-1;
alert(rows);
document.getElementById("span" + (i + 1)).innerHTML = rows;
}
}
You are never referring to the span, so that is why I used
document.getElementById("span" + (i + 1)).innerHTML = rows;

Concatenate loop within loop in jQuery?

I am trying to create a grid like structure. I want to create a loop within a loop and append divs based on if it is a column or a row. Below is my attempt:
for (var row = 0; row < 8; row++) {
$('#board').append('<div class="row">'+ row +'</div>');
}
What I would like to replicate in plain Javascript (code is most likely incorrect, I just want to show an example of what I want):
var board = document.getElementById('board');
for (var row = 0; row < 8; row++) {
board.write('<div class="row">');
for(var col = 0; col < 8; col++) {
var row = document.getElementsByClassName('row');
row.write('<div class="piece">'+col+'</div>')
}
board.write('</div>');
}
It would be useful if I could somehow replicate the document.write() method in jQuery. .append() did not work correctly for me when I tried to include a forloop.
You just need to loop through rows and then cells to build a single html string and than append it only once:
var rows = [], cells = [];
for (var row = 0; row < 8; row++) {
cells = [];
for (var cell = 0; cell < 8; cell++) {
cells.push('<div class="piece">'+ row +'</div>');
}
rows.push('<div class="row">' + cells.join('') + '</div>');
}
$('#board').html(rows.join(''));
DEMO HERE
What I understand you want to end up with a structure like this:
<div id="board">
<div class="row">
<div class="piece"></div>
<div class="piece"></div>
<div class="piece"></div>
(...)
</div>
(...)
</div>
Let's assume you already have a board (<div id="board"></div>).
for( var row = 0; row < 8; row++ ) {
//Create a row
$row = $('<div class="row"></div>');
//Stuff 8 pieces in that row
for( var col = 0; col < 8; col++ ) {
$row.append( $('<div class="piece">' + col + '</div>') );
}
//Add the row to the board
$('#board').append( $row );
}
Edit: In your case you can even simplify it to:
//Stuff 8 rows in the board
for( var row = 0; row < 8; row++ ) {
$('#board').append( $('<div class="row"></div>') );
}
//Stuff 8 pieces in every of the 8 rows
//This can be done because the piece is the same for every row
for( var col = 0; col < 8; col++ ) {
$('.row').append( $('<div class="piece">' + col + '</div>') );
}
jsFiddle: http://jsfiddle.net/3jGnF/
Try the following - if you need to manipulate DOM more specifically, then use JQuery
var board = document.getElementById('board'),
html = '';
for (var row = 0; row < 8; row++) {
html += '<div class="row">';
for(var col = 0; col < 8; col++) {
html += '<div class="piece">'+col+'</div>';
}
html += '</div>';
}
board.innerHTML = html;
Or with JQuery:
var board = $('#board');
...
board.append($(html));

Categories

Resources