Concatenate loop within loop in jQuery? - javascript

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

Related

how to find a td by index in jquery

how can i change the inner html by getting element by index
i want to change the content of cells according to their index values
<table>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</table>
function LFLS() {
// LFLS => load from local Storage
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);//it return values like ("1,2","2,5", etc.)
console.log(key)
row = key.split(",")[0];
col = key.split(",")[1];
//how to get the cell by row and col
}
}
As Sakil said you can use eq(). Try this:
function LFLS() {
// load from local Storage
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
row = key.split(",")[0];
col = key.split(",")[1];
// how to get the cell by row and col
$("table tr").eq(row).children().eq(col).html('NEW VALUE')
}
}
I believe you need the following snippets.
Before your for loop
const rows = $("table tr");
After you obtain row & col variables
const cellToUpdate = rows[row].children[col];
Alternatively, if you're looking to programatically loop through the table you could use the following snippet.
<script type="text/javascript">
const rows = $("table tr");
for( i = 0; i < rows.length; i++ ) {
const currRow = rows[i];
const rowChildren = currRow.children;
for( n = 0; n < rowChildren.length; n++ ) {
const cell = rowChildren[n];
cell.innerHTML = "My new data for row: " + i + " in cell " + n;
}
}
</script>
Is something on the lines of below not going to work for you for some reason?
$("table tr:nth-of-type([your-row])).eq([your-col]).html([your_content]);

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

Unable to print table grid using jQuery

I am unable to print a grid. This is what I am trying to do:
Take the grid size as an input from the user.
Dynamically create the grid based on the input.
Below is a part of the code.
$(document).ready(function() {
$("#grid-input").click(function() {
$(".drawing-area").empty();
var rows = $("#row").val();
var cols = $("#col").val();
if (rows > 0 && cols > 0) {
for (var i = 1; i <= rows; i++) {
var rowClassName = 'row' + i;
$('<tr></tr>').addClass(rowClassName).appendTo('.drawing-area'); //Adding dynamic class names whenever a new table row is created
for (var j = 1; j <= cols; j++) {
var colClassName = 'col' + j;
$('<td width="20px" height="20px" style="border: 1px solid #000"></td>').addClass(colClassName).appendTo('.rowClassName');
}
}
} else {
alert("You haven't provided the grid size!");
}
});
});
});
<table class="drawing-area">
</table>
There is an error in your code, Last brackets are not required.
Append dom at the end of your code,
Try following code
$(document).ready(function() {
$("#grid-input").click(function() {
$(".drawing-area").empty();
var rows = $("#row").val();
var cols = $("#col").val();
if (rows > 0 && cols > 0) {
for (var i = 1; i <= rows; i++) {
var rowClassName = 'row' + i;
var tr = $('<tr>').addClass(rowClassName);
tr.appendTo('.drawing-area'); //Adding dynamic class names whenever a new table row is created
for (var j = 1; j <= cols; j++) {
var colClassName = 'col' + j;
$('<td width="20px" height="20px" style="border: 1px solid #000">').addClass(colClassName).appendTo(tr);
}
}
} else {
alert("You haven't provided the grid size!");
}
});
});
You can try to save the dynamic table row to a variable $tr first and then add the dynamic table column to that $tr variable like:
$("#grid-input").click(function() {
$(".drawing-area").empty();
var rows = $("#row").val();
var cols = $("#col").val();
if (rows > 0 && cols > 0) {
for (var i = 1; i <= rows; i++) {
var rowClassName = 'row' + i;
// Saving dynamic table row variable
var $tr = $('<tr/>').addClass(rowClassName).appendTo('.drawing-area');
for (var j = 1; j <= cols; j++) {
var colClassName = 'col' + j;
$('<td>'+ (i * j) +'</td>').addClass(colClassName)
// Append the new td to this $tr
.appendTo($tr);
}
}
} else {
alert("You haven't provided the grid size!");
}
});
.drawing-area{font-family:"Trebuchet MS",Arial,Helvetica,sans-serif;border-collapse:collapse;width:100%}
.drawing-area td,.drawing-area th{border:1px solid #ddd;padding:8px}
.drawing-area tr:nth-child(even){background-color:#f2f2f2}
.drawing-area tr:hover{background-color:#ddd}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Row: <input type="number" id="row"><br/>
Col: <input type="number" id="col"><br/>
<button id="grid-input">Save</button><br/><br/>
<table class="drawing-area">
</table>

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 />

Alternating Table Rows With Javascript issue

I have the following script working to add odd and even classes to alternating table rows which works fine.
function alternate(){
if(document.getElementsByTagName){
var table = document.getElementsByTagName("table");
var rows = document.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//manipulate rows
if(i % 2 == 0){
rows[i].className = "even";
}else{
rows[i].className = "odd";
}
}
}
}
However a problem arises when there is more than one table on a page. I need the counter to reset for each table on the page so the first row of each table always has the same class (i.e. odd). Currently the second table on the page will just carry on counting rows odd-even so it will start on a different class if the first table has an odd number of rows.
Can anyone help me change this code to achieve this?
Here you go:
function alternate() {
var i, j, tables, rows;
tables = document.getElementsByTagName( 'table' );
for ( i = 0; i < tables.length; i += 1 ) {
rows = tables[i].rows;
for ( j = 0; j < rows.length; j += 1 ) {
rows[j].className = j % 2 ? 'even' : 'odd';
}
}
}
Live demo: http://jsfiddle.net/simevidas/w6rvd/
Alternative solution:
(Substituting the for iteration statements with forEach invocations makes the code more terse. Doesn't work in IE8 though :/.)
function alternate() {
var tables = document.getElementsByTagName( 'table' );
[].forEach.call( tables, function ( table ) {
[].forEach.call( table.rows, function ( row, i ) {
row.className = i % 2 ? 'even' : 'odd';
});
});
}
Live demo: http://jsfiddle.net/simevidas/w6rvd/1/
You have to add a for for each table:
function alternate(){
if(document.getElementsByTagName){
var table = document.getElementsByTagName("table");
// each table
for(a = 0; a < table.length; a++){
var rows = table[a].getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//manipulate rows
if(i % 2 == 0){
rows[i].className = "even";
}else{
rows[i].className = "odd";
}
}
}
}
}
do this work, based on each table
function alternate(){
if(document.getElementsByTagName){
var table = document.getElementsByTagName("table");
var rows = document.getElementsByTagName("tr");
for(var a = 0; a < table.length; a++){
{
for(var i = 0; i < table[a].rows.length; i++){
//manipulate rows
if(i % 2 == 0){
table[a].rows[i].className = "even";
}else{
table[a].rows[i].className = "odd";
}
}
}
} }
}

Categories

Resources