How to create a two-dimensional array within a table? - javascript

I would like to create a table for a Connect Four game, I would like to do this by setting a two-dimensional 7*6 array and put each array within each cell if that makes sense. I am new to Javascript and do not have lot of knowledge in object orientated programming. I am trying to give each cell a xPosition and yPosition (coordinates, perhaps this could be in their "id") so that the game can check if there is a row or column of Blue or yellow.
Code so far, rough attempt:
function make()
{
var table = document.createElement("table");
for (var i = 0; i < 6; i++)
{
var row = table.inserRow();
for (var j = 0; j < 5; j++)
{
var cell = row.insertCell;
}
document.body.appendChild(table);
}
}

Some really quick solution written with jQuery. I pasted whole html, so you can save it out as html file and open in a browser. You can click on cells to see coordinates (0-based).
<html>
<head>
<title>GRID</title>
<style type="text/css">
table tr td { width: 50px; height: 50px; background-color: silver; border: 1px solid black; }
table tr td.over { background-color: yellow; }
table tr td.active { background-color: red; }
.controls { padding: 20px; }
</style>
</head>
<body>
<div class="controls">
left
top
right
bottom
topleft
topright
bottomright
bottomleft
</div>
<table></table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var rows = 6,
cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
$('table tr td').mouseover(function() {
$(this).addClass('over');
}).mouseout(function() {
$(this).removeClass('over');
}).click(function() {
$(this).addClass('active');
});
$(".controls a").click(function() {
var $active = $("table tr td.active");
if($active.length > 0) {
var move = $.parseJSON($(this).attr('data-move'));
if(move.length >= 2) {
$active.each(function() {
var row = parseInt($(this).attr('data-row')) + move[1],
col = parseInt($(this).attr('data-col')) + move[0];
if(col >= cols) col = cols - 1;
if(col < 0) col = 0;
if(row >= rows) row = rows - 1;
if(row < 0) row = 0;
$(this).removeClass('active');
$('table tr').eq(row).find('td').eq(col).addClass('active');
});
}
}
});
});
</script>
</body>
</html>
Notice that if you change rows and cols variables you can draw bigger grids.
I have added controls div with buttons so you can play with directions. First of all you need to mark element as active, and them you can click to move.
There is one bug (or feature in my opinion) that you can mark multiple fields and move them all at once.
It's good base to start with!

Related

I am trying to create a table of 8x8 squares in HTML using script

I thought maybe doing this with a for loop like that
<table>
<script>
for (var i; i = 0; i < 8; i++) {
document.write("<tr>")
for (var j; j = 0; j < 8; j++) {
document.write("<td></td>")
}
document.write("<tr>")
}
</script>
</table>
This code doesn't seem to work. Please understand that I am not at all fluent in js, so a solution with an explenationn will really help.
document.write would not work as you have tried here, it won't write the <tr> tags at the place you've mentioned either.
You need to modify the DOM, specifically the table element.
Below code, takes a reference of table and appends the 8 rows and 8 cols in it.
document.querySelector("table").innerHTML = new Array(8).fill("<tr>" + new Array(8).fill("<td></td>").join("") + "</tr>").join("");
td {
border: 1px solid;
padding: 5px;
}
<table></table>
PS: This is a basic example to get you started, there are better ways to achieve this. you should look more into DOM Manipulation in JS.
Use DOM manipulation methods and make sure to put <script> right before the closing tag of <body> instead of inside <tabl> , here is a working example:
let table = document.getElementById('table');
for (let i = 0; i < 8; i++) {
let row = document.createElement('TR');
table.appendChild(row);
for (let i = 0; i < 8; i++) {
var cell = document.createElement('TD');
row.appendChild(cell);
}
}
td {
border: 1px solid #333;
padding: 5px;
}
<table id="table"></table>
document.write() will never create a child element inside the <table> element, you can create a child element for a parent with appendChild().
Here an example with pure JavaScript:
for (var i = 0; i < 8; i++) {
var row = document.createElement("tr");
document.getElementById('tbl').appendChild(row).setAttribute("id", 'row_' + i);
for (var j = 0; j < 8; j++) {
var column = document.createElement("td");
document.getElementById('row_' + i).appendChild(column);
}
}
table {
border: 1px solid black;
}
td {
border: 1px solid blue;
padding: 3px;
margin: 2px;
}
<table id='tbl'></table>
Here, the script will create a child <tr> for the <table>, then you can create child <td> for the <tr>.

How to delete table cells properly

I am trying to delete table rows and table column. For that i have written two functions. The DelelteRow() and DeleteColumn() delete the cells which have
index greater then zero. But actually one row or column should be deleted at a time. can some one modify my code.
DeleteRow:
function DeleteRows() {
var tbl = document.getElementById('myTable'),
lastRow = tbl.rows.length - 1,
i;
for (i = lastRow; i > 0; i--) {
tbl.deleteRow(i);
}
}
DeleteColumn:
function DeleteColumns() {
var tbl = document.getElementById('myTable'),
lastCol = tbl.rows[0].cells.length - 1,
i, j;
for (i = 0; i < tbl.rows.length; i++) {
for (j = lastCol; j > 0; j--) {
tbl.rows[i].deleteCell(j);
}
}
Something like this will delete one row/column at a time. Your question is not entirely clear which row/column you'd like removed, but your code implies you only want the last row/column removed.
var delRowBtn = document.querySelector('.delRow');
delRowBtn.addEventListener('click', deleteLastRow);
var delColBtn = document.querySelector('.delCol');
delColBtn.addEventListener('click', deleteLastColumn);
var tbl = document.querySelector('table');
function deleteLastRow() {
tbl.deleteRow(tbl.rows.length - 1);
}
function deleteLastColumn() {
var lastCol = tbl.rows[0].cells.length - 1;
for (var i = 0; i < tbl.rows.length; i++) {
tbl.rows[i].deleteCell(lastCol);
}
}
html, body {
font-size: 24px;
}
table {
margin-top: 30px;
}
td {
padding: 10px;
outline: 1px solid lightgrey;
}
<button class="delRow">Delete Row</button>
<button class="delCol">Delete Column</button>
<table>
<tbody>
<tr>
<td>r0c0</td>
<td>r0c1</td>
<td>r0c2</td>
<td>r0c3</td>
<td>r0c4</td>
</tr>
<tr>
<td>r1c0</td>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
<td>r1c4</td>
</tr>
<tr>
<td>r2c0</td>
<td>r2c1</td>
<td>r2c2</td>
<td>r2c3</td>
<td>r2c4</td>
</tr>
</tbody>
</table>

Inline style edited with JavaScript is being ignored

I'm trying to use document.getElementByClassId().style.color to change the color of an element in my HTML document. I can see that it does add an inline style tag to the element but they are seemingly ignored by the browser.
I tried using the !important tag but that changed nothing. Here is my HTML document. I changed my CSS for the elements I want to modify into inline tags but they are ignored as well. Everything else works so far.
Here is my code (I'm a beginner please go easy on me :/).
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel">';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.color = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>
You have to style the backgroundColor instead of color, because the cells don't contain any text, to which the color would be applied to
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel"></td>';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.backgroundColor = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>

Creating table with javascript and add id and class to each td

I'm trying to create a chess game in javascript. I created a chessboard and the next step is to add an id's and classes to created td's.
Here is the code:
<html>
<head>
<title> Play Chess! </title>
<meta charset="utf-8">
<link rel='stylesheet' href='css/styles.scss' type='text/css'/>
</head>
<body>
<script>
var table ='';
var rows =8;
var cols=8;
for (var r = 0; r<rows;r++){
table +='<tr>';
for(var c=0;c<cols;c++){
table+='<td>' +''+'</td>';
}
table+='</tr>';
}
document.write("<table border=1>"+table+'</table>');
</script>
</body>
</html>
I know I can simply do this with html, but it's too much code and I belive there is other way to do this.
Here is a solution with plain JavaScript (no jQuery). Put the script just before the closing </body> tag. This does not use document.write which really is to be avoided. Instead the HTML has an empty table with an id attribute, which then is populated through script.
var rows =8;
var cols=8;
var table = document.getElementById('board');
for (var r = 0; r<rows; r++){
var row = table.insertRow(-1);
for (var c = 0; c<cols; c++){
var cell = row.insertCell(-1);
cell.setAttribute('id', 'abcdefgh'.charAt(c) + (rows-r));
cell.setAttribute('class', 'cell ' + ((c+r) % 2 ? 'odd' : 'even'));
}
}
table {
border-spacing: 0;
border-collapse: collapse;
}
.cell { width: 20px; height: 20px; }
.odd { background-color: brown }
.even { background-color: pink }
<table id="board"></table>
As a bonus it has the chessboard altering colors, and the id values are running from a1 (bottom-left) to h8 (top-right)
If you can solve this issue by coding the layout directly inside your HTML file, you should definitely do that instead of building it dynamically in JavaScript. This is hugely less error-prone.
That being said, solving this using jQuery is not too hard:
var sideLength = 8;
var table = $('<table>');
$('#root').append(table);
for (var i = 0; i < sideLength; i++) {
var row = $('<tr>');
table.append(row);
for (var j = 0; j < sideLength; j++) {
row.append($('<td>'));
}
}
td {
border: 1px black solid;
width: 10px;
height: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='root'></div>

Adding elements on loop jQuery

I am trying to generate a row of 16 boxes on load of webpage.
Here is my code:
var box = $("<div></div>").addClass("box");
$(document).ready(function(){
for(var i = 0; i < 16; i++) {
$("#container").append(box);
}
});
I also tried this within the for loop's code block:
if($("#container:contains(box)")) {
$(box).append(box);
}
I kind of understand why this does not work. That var box is only referencing an element and is not a copy of an element?
As you can likely tell, I'm new. I would really appreciate some pointers on how I can achieve this. Thanks.
Why not just use like this?
for(var i = 0; i < 16; i++) {
$("#container").append('<div class="box box-'+i+'" />');
}
You're appending the same div over and over. That will just move it (in this case, right back where it was). For a new div each time:
$(document).ready(function(){
var ctr = $('#container');
for(var i = 0; i < 16; i++) {
ctr.append("<div class='box'></div>");
}
});
$(document).ready(function() {
var ctr = $('#container');
for (var i = 0; i < 16; i++) {
ctr.append("<div class='box'></div>");
}
});
.box {
margin: 10px;
height: 25px;
width: 25px;
background-color: red;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container"></div>
I recommend against using append in a loop, bad performance. I suggest this:
var buffer = [];
for(var i = 0; i < 16; i++) {
buffer.push("<div class='box'></div>");
}
var html=buffer.join('');
$('#container').append(html);

Categories

Resources