Creating table or multi-dimensional grid using JavaScript - javascript

I'm trying to create a word search puzzle and am beginning by generating a table of random letters. I want to have a table of any number by number, so 10X10 for example, but so far I'm only able to generate a column and can't figure out how to create more columns or the entire grid.
var firstCol = [];
for (var i = 0; i <= 10; i++){
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
var random = parseInt(Math.random()*characters.length);
var letter = characters.charAt(random); //returning random letter
var innerArrays = ['<td>' + letter + '</td>'];
firstCol.push(innerArrays);
};
for (var i = 0; i <= 10; i++){
document.getElementById('wsBox').innerHTML +=
'<tr>'+ firstCol[i] + '</tr>';
};
and this is my HTML...
<table>
<tbody id="wsBox">
</tbody>
</table>

This is a very basic code.
var cols = 10;
var rows = 10;
var html = "";
for(var i =0; i <= rows; i++) {
html += '<tr>';
for(var h=0; h<= cols; h++) {
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
var random = parseInt(Math.random()*characters.length);
var letter = characters.charAt(random); //returning random letter
html += '<td>' + letter + '</td>';
}
html += '</tr>';
}
document.getElementById('wsBox').innerHTML += html;

Here's working code:
http://jsfiddle.net/42dj7jy8/3/
Script
var rows = [];
var colStr = null;
for(var j = 0; j <= 10; j++) {
colStr = "";
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
for (var i = 0; i <= 10; i++){
var random = parseInt(Math.random()*characters.length);
var letter = characters.charAt(random); //returning random letter
var cell = '<td>' + letter + '</td>';
colStr += cell;
};
rows.push('<tr>' + colStr + '</tr>');
}
document.getElementById('wsBox').innerHTML += rows.join("");
Some CSS to wash it down with
td {
border: 1px solid black;
padding: 4px;
text-align: center;
vertical-align: middle;
width: 20px;
height: 20px;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
Here's output

This uses arrays to build the cells and rows of the grid which are joined together with the join method. Simply pass the dimensions of the grid into the function. One loop only.
function createGrid(x, y) {
var rows = [], cells = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
// a complete grid is x * y dimensions
for (var i = 0, l = x * y; i < l; i++) {
letter = characters.charAt(Math.random() * characters.length);
cells.push('<td>' + letter + '</td>');
// when we reach the last column of the row
// push the cells into the row array and reset
// the cells array
if (i !== 0 && (i + 1) % x === 0) {
rows.push('<tr>' + cells.join('') + '</tr>');
cells = [];
}
}
return rows.join('');
}
Grab the element and use insertAdjacentHTML to add the compiled grid HTML.
var tbody = document.getElementById('wsBox');
tbody.insertAdjacentHTML('beforeend', createGrid(10, 10));
DEMO - 10 x 10 grid
DEMO - 3 x 4 grid

Related

Multiplication Table in javascript and how about to align the row

I tried to a do Multiplication Table in JS and I want to print in <p> element out (Use DOM and not use document.write method).
I tried to use " " or "\t" to align column , but when number is double digit (from x3 column) , it got typographic issue.
Does it any ways could solve this problem?
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
for (var j = 1; j <= 9; j++) {
s = s + j + "*" + i + " = " + (i * j) + " ";
}
s = s + "<br>";
}
p1.innerHTML = s;
<pre id="printout"></pre>
Instead of printing table column wise, print row wise.
And wrap your each table in a div, so that aligning them becomes easy.
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
s = s + "<div>";
for (var j = 1; j <= 9; j++) {
s = s + i + "*" + j + " = " + (i*j) + "<Br/>" ;
}
s = s + "</div>";
}
p1.innerHTML = s;
Little bit CSS
#printout {
display:flex;
flex-wrap:wrap;
}
#printout div {
padding:10px;
min-width:100px
}
https://jsfiddle.net/wkg92rud/
Inspiring from #Andreas suggestion, Using <table>
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
let row = document.createElement("tr");
for (var j = 1; j <= 9; j++) {
let col = document.createElement("td");
col.innerText = j + "*" + i + " = " + (i * j);
row.append(col);
}
p1.append(row);
}
td {
padding: 2px 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table id="printout"></table>
</body>
</html>
#Dalvik method is the correct way, styling and alignment should be done through CSS.
However, in other environments like command line, or if you are doing this as an exercise to learn JS you can use string padding, here is an example:
const p1 = document.getElementById("printout");
const LONGEST_ENTRY = 9; // Longest string you will have is 9 characters long
const entries = []
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
const entry = `${j}*${i} = ${(i*j)}`.padEnd(LONGEST_ENTRY, " ") ; // use string interpolation, then pad the string with spaces until the length of LONGEST_ENTRY is reached
entries.push(entry); // store all the entries in an array
}
entries.push("<br/>"); // add a line break at the end of each row
}
p1.innerHTML = entries.join(''); // join all the elements
Here is a jsfiddle as an example

Using jQuery to Generate a Grid of DIVs, but Get Wierd Behavior if it Isn't 10 x 10

I'm using jQuery to generate a grid of divs that I will then style to become the board of a game. It works fine when I set the grid to 10 x 10, but when I increase the number of squares, even by one, the second column from the left either doesn't display at all (although the html is fine), or it extends from the bottom of the grid down instead of up.
I've tried messing with the stylesheet and pretty much every variable in the code to no avail. Any help would be appreciated.
$(document).ready(function() {
var row_count = 11;
var base = document.getElementById('base');
var square = '<div class="square"></div>';
var col_count = 11; // Sets the number of columns
while (col_count >= 0) { //Outer loops controls the columns.
row_count = 11; // sets the number of rows
while (row_count >= 0) {
$('<div class="square" id = "in_col' + '_' + col_count + '_' + row_count + '"></div>', {
"class": "square"
}).appendTo('#base');
row_count--;
}
col_count--;
}
// These two values, for posx and posy are the positioning
// coordinates for the squares of the grid
var posx = 10;
var posy = 10;
var col = 0; // Initiates the column counter for the below while loop
while (col <= 11) { // must match var col_count above
$.each($('div[id^="in_col_' + col + '"]'), function() {
$(this).css('top', posy);
$(this).css('left', posx);
posy += 41;
});
posy = 10;
posx += 41;
col++;
}
});
.square {
border: 1px solid black;
height: 40px;
width: 40px;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='base'>
</div>
Fiddle of example
I refactored the code a bit, using for loops instead so we don't have to keep track of iteration variables. I also used float: left; on the tiles and clear: both; whenever we want to wrap down to a new line.
Javascript
$(document).ready(function() {
var col_count = 11; //Sets the number of columns
var row_count = 11; //sets the number of rows
var base = $('#base');
var square = '<div class="square"></div>';
for(var i = 0; i < col_count; i++){
for(var j = 0; j < row_count; j++){
var tile = $(square);
if(j === 0) tile.addClass('newRow');
base.append(tile);
}
}
});
CSS
.square {
border: 1px solid black;
height: 40px;
width: 40px;
float: left;
margin-top: -1px;
margin-left: -1px;
}
.newRow {
clear: both;
}
fiddle: https://jsfiddle.net/e0g6y9th/
Problem is in $.each($('div[id^="in_col_' + col + '"]'), function() {
col_10 is called 2 times. Change it to $.each($('div[id^="in_col_' + col + '_"]'), function() {, a more restrictive regex
$(document).ready(function() {
var row_count = 11;
var base = document.getElementById('base');
var square = '<div class="square"></div>';
var col_count = 11; // Sets the number of columns
while (col_count >= 0) { //Outer loops controls the columns.
row_count = 11; // sets the number of rows
while (row_count >= 0) {
$('<div class="square" id = "in_col' + '_' + col_count + '_' + row_count + '"></div>', {
"class": "square"
}).appendTo('#base');
row_count--;
}
col_count--;
}
// These two values, for posx and posy are the positioning
// coordinates for the squares of the grid
var posx = 10;
var posy = 10;
var col = 0; // Initiates the column counter for the below while loop
while (col <= 11) { // must match var col_count above
$.each($('div[id^="in_col_' + col + '_"]'), function() {
$(this).css('top', posy);
$(this).css('left', posx);
posy += 41;
});
posy = 10;
posx += 41;
col++;
}
});
.square {
border: 1px solid black;
height: 40px;
width: 40px;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='base'>
</div>
The selector in your $.each loop is matching columns multiple times. A simple solution will be to zero-pad the numbers in your ids:
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
Then change
$('<div class="square" id = "in_col' + '_' + col_count + '_' + row_count + '"></div>', {
"class": "square"
}).appendTo('#base');
To
$('<div class="square" id = "in_col' + '_' + pad(col_count,3) + '_' + pad(row_count,3) + '"></div>', {
"class": "square"
}).appendTo('#base');
And
$.each($('div[id^="in_col_' + col + '"]'), function() {
to
$.each($('div[id^="in_col_' + pad(col,3) + '"]'), function() {
Here's a working fiddle: https://jsfiddle.net/xc9gyv8p/4/
Here's my take
fiddle
$(document).ready(function() {
var row_count = 11;
var col_count = 11;
var x = 0;
var y = 0;
var offX = 41;
var offY = 41;
for(var i = 0; i < col_count; i++){
$('#base').append('<div id="col_'+i+'" class="col" style="left:'+x+'px"><div>');
x += offX;
y = 0;
for(var j = 0; j < row_count; j++){
$('#col_'+i).append('<div class="square" id="row_'+j+'" style="top:'+y+'px"></div>');
y += offY;
}
}
});
.col{
position: absolute;
}
.square {
border: 1px solid black;
height: 40px;
width: 40px;
position: absolute;
}
Yours is more a mathematical problem. My version is much easier to understand, here is a fiddle.
go row by row and column by column in each row. so var i is each row and var j is each column in the row (starting every time by 1 and count up till reach var col_count.
$(document).ready(function() {
var row_count = 11;
var col_count = 11;
var size = 41;
var base = document.getElementById('base');
for (var i=1; i<=row_count; i++) {
for (var j=1; j<=col_count; j++) {
$('<div class="square" id = "in_col' + '_' + j + '_' + i + '"></div>')
.addClass('square')
.css({
'left': j*size,
'top': i*size
})
.appendTo('#base');
}
}
});
to select each elements in column 1 use div[id^="in_col_1_"]. I would recommend you to work with data attributes by changing the code to:
$(document).ready(function() {
var row_count = 11;
var col_count = 11;
var size = 41;
var base = document.getElementById('base');
for (var i=1; i<=row_count; i++) {
for (var j=1; j<=col_count; j++) {
$('<div class="square" id = "in_col' + '_' + j + '_' + i + '"></div>')
.addClass('square')
.attr('data-col', j)
.attr('data-row', i)
.css({
'left': j*size,
'top': i*size
})
.appendTo('#base');
}
}
});
so you can easily select elements in row 1 by div[data-row="1"] and column 1 by div[data-col="1"]. Have a look at this fiddle.
insted for running while loop backward run it forward, it will fix your problem
var row_count = 0;
var col_count = 0; // Sets the number of columns
while (col_count <= 10){ //Outer loops controls the columns.
row_count = 0; // sets the number of rows
while (row_count <= 10) { // Inner loop controls the cells in each column.
$('<div class="square" id = "in_col' + '_' + col_count + '_' + row_count +'"></div>', {"class":"square"}).appendTo('#base');
row_count++;
}
col_count++;
}
IrkenInvader, thanks, I went with your solution, much cleaner than what I had originally and obviates the need for the bit of code (the regex in the jQuery selector) that was causing the problem.
$(document).ready(function(){
var col_count = 11;// Sets the number of columns
var row_count = 11; //sets the number of rows
var base = $('#base');
for(var i = 0; i < col_count; i++) {
for (var j = 0; j < row_count; j++) {
var square = '<div class="square" id = "in_col' + '_' + j + '_' + i +'"></div>';
var tile = $(square);
if (j === 0) tile.addClass('newRow');
base.append(tile);
}
}
});

Add alphabets dynamically as html row increments

How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";

Create html table from comma separated strings javascript

I am trying to write a Javascript function which writes the text to (eventually) create the following html tables (I will be passing different length arguments to it to create hundreds of tables):
<table>
<tr><td><u>School</u></td>
<td><u>Percent</u></td>
<tr><td>School 1: </td>
<td>Percent1</td></tr>
<tr><td>School 2: </td>
<td>Percent2</td></tr>
<tr><td>School 3: </td>
<td>Percent3</td></tr>
</table>
The inputs that I have are comma separated strings:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
The function needs to be passed school_list and pct_list, and return a string of the html table code above.
Something like this:
var schoolArr = school_list.split(',');
var pctArr = pct_list.split(',');
var table = "<table>";
for (var i=0; i< schoolArr.length; i++) {
table = table + "<tr><td>"+ schoolArr[i]+"</td><td>"+ pctArr[i] +"</td></tr>";
}
table = table + "</table>";
return table;
You can try below code with Jsfiddle demo ::
function createTable(tab) {
var tar = document.getElementById(tab);
var table = document.createElement('TABLE');
table.border = '1';
var tbdy = document.createElement('TBODY');
table.appendChild(tbdy);
for (var j = 0; j < 4; j++) {
var tr = document.createElement('TR');
tbdy.appendChild(tr);
for (var k = 0; k < 2; k++) {
var td = document.createElement('TD');
td.width = '100';
if (k == 0) td.innerHTML = "School" + (j + 1);
else td.innerHTML = "Percent" + (j + 1);
tr.appendChild(td);
}
}
tar.appendChild(table);
}
createTable('tab');
<div id="tab"></div>
var schools = school_list.split(/,\s*/g).join('</td><td>');
var pcts = pct_list.split(/,\s*/g).join('</td><td>');
return '<table><tr><td>' + schools + '</td></tr><tr><td>' + pcts + '</td></tr></table>'
or a better approach is to construct the whole table in DOM and place it in document directly.
function appendTD(tr, content) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
var table = document.createElement('table');
school_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
pct_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
someParent.appendChild(table);
var numberOfSchools = school_list.split(',');
var numberOfPercent = pct_list.split(',');
var htmlOutput= '<table><tr><td><u>School</u></td><td><u>Percent</u></td>';
for(var i = 0 ; i < numberOfSchools.length; i++)
{
htmlOutput += "<tr><td>" + numberOfSchools[i] + "</td>";
htmlOutput += "<td>"+numberOfPercent[i] +"</td></tr>"
}
htmlOutput += "</table>"
And return htmlOutput
Here's a DOM method, highlighs why innerHTML is so popular. DOM methods are pretty fast in execution lately, but the amount of code is a bit tiresome unless there's a good reason to use it.
The amount of code can be significantly reduced with a couple of helper functions so it is on par with innerHTML methods:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
function makeTable(schools, percents) {
// Turn input strings into arrays
var s = schools.split(',');
var p = percents.split(',');
// Setup DOM elements
var table = document.createElement('table');
var tbody = table.appendChild(document.createElement('tbody'));
var oRow = document.createElement('tr');
var row;
oRow.appendChild(document.createElement('td'));
oRow.appendChild(document.createElement('td'));
table.appendChild(tbody);
// Write header
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode('School'));
row.childNodes[1].appendChild(document.createTextNode('Percent'));
// Write rest of table
for (var i=0, iLen=s.length; i<iLen; i++) {
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode(s[i]));
row.childNodes[1].appendChild(document.createTextNode(p[i]));
}
document.body.appendChild(table);
}
It can be called after the load event, or just placed somewhere suitable in the document:
window.onload = function() {
makeTable(school_list, pct_list);
}

Trying to take the number from the first column of each row, and insert it as the id of the <tr> element

Here's my code. I am trying to take the value of the innerHTML for each row of a column in my table, and then add this to a <tr> element as <tr id="1"> <tr id="47">, etc
window.onload = function inventorytable() {
var tableRows = document.getElementById("inventorytable").rows;
var idxarray = "";
for(var i = 1, l = tableRows.length; i < l; i++) {
var tds = tableRows[i].cells;
tds[7].innerHTML += " Ghz"
tds[8].innerHTML += " GB"
tds[10].innerHTML += " Mhz"
idxarray = idxarray += tds[0].innerHTML //THIS IS WHERE I AM NOT SURE WHAT TO DO
}}
How do I take the information contained in tds[0].innerHTML for each row, and put it as that row's id?
I'm a little confused. Are you trying to take the inner-html of column 0 of each row and make that the id (prepended with row-) of the parent tr? If so would this do the trick?...
window.onload = function inventorytable() {
var tableRows = document.getElementById("inventorytable").rows;
for(var i = 1, l = tableRows.length; i < l; i++) {
var tds = tableRows[i].cells;
tds[7].innerHTML += " Ghz"
tds[8].innerHTML += " GB"
tds[10].innerHTML += " Mhz"
tableRows[i].id = 'row-' + tds[0];
}
}

Categories

Resources