MineField with Js - javascript

I am trying to create a minefield game with javascript.
When I click on clear ro**w it gives "passed" but sometimes "died" too or clicking on **mined row gives sometimes "passed". It's supposed to give only "passed" with clear and "died" with mined row.
I can't figure out the reason..
Could you see it?
Here is my code so far:
var level = 9;
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id', 'myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 50);
if (j <= 15) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "1");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("td");
for (p = 0; p < rows.length; p++) {
var currentRow = table.rows[p];
var createClickHandler = function (row) {
return function () {
var cell = row.getElementsByTagName("td")[1];
var id = cell.innerHTML;
if (id == "mined") {
alert("Died");
} else {
alert("Passed!");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
JSFiddle Here:
http://jsfiddle.net/blowsie/ykuyE/
Thanks in advance!

Its' this line, which causes the faulty behaviour: var cell = row.getElementsByTagName("td")[1]; Everytime a click is made, the [1] selects the 2nd cell of a column, no matter which cell was actually clicked.
I modified your fiddle: http://jsfiddle.net/ykuyE/1
The onclick handler is now applied to the individual cell directly, when the table is created.
cell.onclick = function() {
if (this.innerHTML == "mined") {
alert("Died");
} else {
alert("Passed!");
}
}

Related

js button generator with functions

I got the code to generate the table with buttons i wanted,
but i also want to get a "onlick="cell_id(" + j +"," + i ")" function within the <button> element using js.
The j and i variables are to mark the row and column where the click came from and also used to create the table.
the code:
function tableCreate() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var j = 0; j <= 10; j++) {
var row = document.createElement("tr");
for (var i = 0; i <10; i++) {
var cell = document.createElement("td");
var button = document.createElement("button");
button.innerHTML = j +"-"+i;
cell.appendChild(button);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function cell_id(x,y){
window.alert('x:'+x+ ' y:'+y)
}
code from https://stackoverflow.com/a/61549235/12825970
You can attach a listener to each button element:
function tableCreate() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var j = 0; j <= 10; j++) {
var row = document.createElement("tr");
for (var i = 0; i <10; i++) {
var cell = document.createElement("td");
var button = document.createElement("button");
button.innerHTML = j +"-"+i;
setupListener(button);
cell.appendChild(button);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function setupListener(button, i, j) {
button.addEventListener('click', () => {
cell_id(button, i, j);
});
}
function cell_id(button, x, y){
msg('x:'+x+ ' y:'+y)
}
This approach works, but is expensive if you have a lot of buttons. For a more advanced approach, you can store the i and j as data attributes on the button, then use a single click event on the entire table. You can filter the events to check if they came from a "source" button. I'll leave that up to you if it's an option you want to pursue.

Javascript generated table - How to update other cells in a row when a number input value in this row changes

I am facing a problem for this day I am creating a pop-up cart with a table, I create an array with
ID | NAME | QUANTITY | PRICE
then I generate the table from this array with javascript.My problem is I want to be able to update the price and the total when I change the quantity for a specific item line (= quantity in the table row). This should work for all generated table rows.
This is my javascript code:
var cartCount = 0;
var Total = 0;
var id = 1;
var labels = ['Name', 'Quantity', 'Price'];
var items;
var cartElement = document.getElementById('cartDisplay');
var counterElement = document.getElementById('counterDisplay');
function cartClick(name, quantity, price) {
const x = {
id: id,
name: name,
quantity: quantity,
price: price
};
if (Obj.some(e => e.name === x.name)) {
console.log('already there');
} else {
Obj.push(x);
cartCount = cartCount + 1;
Total = Total + x.price;
id = id +1;
buildTable(labels, Obj, document.getElementById('modalBODY'));
items = Obj;
console.log(items);
}
CheckCart(cartCount);
console.log(cartCount);
}
function CheckCart(counter) {
if (counter > 0) {
cartElement.style.display = "block";
counterElement.innerHTML = counter;
} else {
cartElement.style.display = "none";
}
}
function buildTable(labels, objects, container) {
container.innerHTML = '';
var table = document.createElement('table');
// class table
table.classList.add("cartTable");
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var theadTr = document.createElement('tr');
for (var i = 0; i < labels.length; i++) {
var theadTh = document.createElement('th');
theadTh.classList.add("cartTh");
theadTh.setAttribute("colSpan", "2");
theadTh.style.padding = '12px';
theadTh.innerHTML = labels[i];
theadTr.appendChild(theadTh);
}
thead.appendChild(theadTr);
table.appendChild(thead);
for (j = 0; j < objects.length; j++) {
var tbodyTr = document.createElement('tr');
for (k = 0; k < labels.length; k++) {
var tbodyTd = document.createElement('td');
tbodyTd.classList.add("cartTd");
tbodyTd.setAttribute("colSpan", "2");
tbodyTd.style.padding = '12px';
if (labels[k] === "Quantity") {
var qinput = document.createElement('input');
qinput.setAttribute("type", "number");
qinput.setAttribute("min", "0");
qinput.setAttribute("max", "10");
qinput.setAttribute("id", "quantityInput");
qinput.setAttribute("value", objects[j][labels[k].toLowerCase()]);
tbodyTd.appendChild(qinput);
} else {
tbodyTd.innerHTML = objects[j][labels[k].toLowerCase()];
}
tbodyTr.appendChild(tbodyTd);
}
tbody.appendChild(tbodyTr);
}
table.appendChild(tbody);
var tfoot = document.createElement('tfoot');
var footTr = document.createElement('tr');
var footTh = document.createElement('th');
var footTd = document.createElement('td');
footTd.setAttribute("id", "totalElement")
tbodyTd.setAttribute("colSpan", "3");
footTh.setAttribute("colSpan", "4");
footTd.innerHTML = Total;
footTh.innerHTML = 'TOTAL';
footTd.classList.add("cartTd");
footTd.classList.add("footerTable");
footTh.classList.add("cartTh");
footTr.appendChild(footTh);
footTr.appendChild(footTd);
tfoot.appendChild(footTr);
table.appendChild(tfoot);
container.appendChild(table);
var beforeText = document.createElement("p");
beforeText.style.marginTop = '5px';
beforeText.innerHTML = "Requests";
container.appendChild(beforeText);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.style.width = '100%';
input.style.padding = '6px';
input.setAttribute("placeholder", "No onion, no tomato...");
container.appendChild(input);
}
I solved a similar problem by creating a rowid and when the user clicks into the row I check for changes. Here the main idea
tableRow.setAttribute("id", "row" + idTable + "_" + tableRow.rowIndex); // for easy handling and selecting rows
tableRow.addEventListener("click", function(){ ... here check for what ever change});
You could also go for a specific change in just one cell, so attach the eventlistener to each quantity cell and read the new value, validate and update other fields then
qinput.addEventListener("change", function(){ ... here check for what ever the change triggers });
EDIT fortheOP:
A generic example for adding an event listener to a tablerow this marks the selected table line red (class table-danger) and removes the colour from allother previous selected lines:
tableRow.addEventListener("click", function(){
tRowData = [];
if(this.classList.contains("table-danger")) {
this.classList.remove("table-danger");
return;
} else {
var nodeParent = this.parentNode;
var trows= nodeParent.getElementsByTagName("tr");
for(var i = 0; i < trows.length;i++) {
trows[i].classList.remove("table-danger");
}
this.classList.add("table-danger");
var cells = this.getElementsByTagName("td");
for ( i = 0; i < cells.length; i++) {
tRowData.push(cells[i].innerHTML); // e.g.: Here you could place your update routine
}
tRowData.push(this.getAttribute("id"));
tRowData.push(this.rowIndex);
return tRowData;
}
});

Having trouble trying to style duplicates

I'm checking for duplicates in a table. What I'm trying to accomplish is when I display the first column if it is the same value as the previous row I don't want to display the value. I'm finding the duplicates but I get an error when I try to hide them by using display. style ="none"; My code is below.
I'm Thanking You In Advance
PD
var data=[['e',0,1,2,3,4], ['a',54312,235,5,15,4], ['a',6,7,8,9,232],
['a',54,11235,345,5,6], ['b',0,1,2,3,4], ['b',54312,235,5,15,4],
['c',62,15,754,93,323], ['d',27,11235,425,18,78], ['d',0,1,2,3,4],
['d',54312,235,5,15,4], ['e',6,7,8,9,232], ['e',54,11235,345,5,6],
['e',0,1,2,3,4], ['e',54312,235,5,15,4], ['e',62,15,754,93,323],
['e',27,11235,425,18,78]];
//Create a HTML Table element.
var table = document.createElement("TABLE");
var somedata = document.createElement("TD");
var dvTable = document.getElementById("dvTable");
var elems = document.getElementsByClassName("tableRow");
//Get the count of columns.
var columnCount = data[0].length;
//Add the data rows.
for (var i = 0; i < data.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
//Searching for duplicates
var num = data[i][0];
for (var otherRow = i + 1; otherRow < data.length; otherRow++) {
var dup = data[otherRow][0];
console.log("What is the dup" + dup);
if (num === dup)
{
console.log("duplicate");
dvTable[i].style.display = "none";
}
}
var cell = row.insertCell(-1);
cell.innerHTML = data[i][j];
cell.innerHtml = myZero;
}
}
dvTable is an HTML table element. You can't access the row using dvTable[i].
Try -
dvTable.rows(i).cells(j).style.display = none;

Calculate a new AveValue in TableCell while adding new Columns using JavaScript-not JQuery

I have a <th> header row with a stated class, and one fixed row with a stated class. Both are contenteditable. I'm adding new rows and new columns. I want to calculate the AverageValue in the final cell. I have tried the code on a fixed number of rows and it works, but when I try it this way it is only taking in the number of columns, not the DATA inserted. It is also not recognizing the row DATA. I'm clearly missing a function?!
I'm at the stage where I need an extra pair of eyes.
JavaScript:
func = function() {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function() {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-");
}
}
createCell = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute('placeholder', '' - '');
cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute("placeholder", "-");
cell.appendChild(div); // append DIV to the table cell
}
addColumn = function() {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
}
}
}
HTML:
<table class="tg" id="mytable">
<tr>
<th class="tg-s6z2" contenteditable="true">Student Name</th>
<th class="tg-s6z2" contenteditable="true">Student ID</th>
<th class="tg-s6z2" contenteditable="true">Assignment 1</th>
<th class="tg-s6z2" contenteditable="true">Final Grade</th>
</tr>
<tr>
<td class="tg-031e" contenteditable="true">Student1</td>
<td class="tg-031e" contenteditable="true">StudentNo</td>
<td class="tg-0ord" contenteditable="true"></td>
<td class="tg-0ord" contenteditable="true"></td>
</tr>
</table>
<button id="btnFinalGrade" class="btn btn-action" onClick="func();">Final Grade</button>
<button id="btnaddRow" class="btn btn-action" onclick="addRow();">AddRow</button>
<button id="btnaddColumn" class="btn btn-action" onclick="addColumn();">AddColumn</button>
You were adding a div to td element which was throwing error while executing this line document.getElementById("mytable").rows[j].cells[i].innerHTML
which returns a div element not the text you entered!
No need to add a div, Here is the updated code,
func = function () {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function () {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-","tg-031e");
}
}
createCell = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute('placeholder', '' - '');
//cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute("placeholder", "-");
//cell.appendChild(div); // append DIV to the table cell
}
addColumn = function () {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-031e");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-s6z2");
}
}
}

Outputting a 3D array as a table

Im making a blackjack game for an assignment and have arrays for leaderboard and cards.
I want to print the leader board like this. CARDS(in individual cells)| TOTAL.
help would be appreciated, thanks
function makeTable(leaderBoard) {
var table = document.createElement('table');
for (var i = 0; i < leaderBoard.length; i++) {
var row = document.createElement('tr');
for (var j = 0; j < leaderBoard[i].length; j++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[i][j];
row.appendChild(cell);
}
table.appendChild(row);
}
document.getElementById('leaderBoard').innerHTML = table;
}
Maybe the example input isn't in the correct format, but reusing a predefined table and html table functions such as insertRow and insertCell (not necessarily better, but they can be easier on the eye than createElement and append) :
<div id="leaderBoard"><table id=leaderTable></table></div>
function updateleaderboard(leaderBoard) {
var table = document.getElementById('leaderTable');
while(table.rows.length > 0) table.deleteRow(0); //remove prev values, if any
for (var i = 0; i < leaderBoard.length; i++) { //If the function is always used on a winner (no ties), the loop isn't really needed
var row =table.insertRow();
var arrCards = leaderBoard[i++];
var total = row.insertCell();
total.className = 'res';
total.textContent = leaderBoard[i];
arrCards.forEach(function(c,ind){
row.insertCell(ind).textContent = c;
});
}
}
var cards = [['Q','4','5'],19];
updateleaderboard(cards);
Fiddle
function makeTable(leaderBoard) {
var table = document.createElement('table');
var row = document.createElement('tr');
for (var i = 0; i < leaderBoard[0].length; i++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[0][i];
row.appendChild(cell);
}
var cell = document.createElement('td');
cell.textContent = "Total: " + leaderBoard[1];
row.appendChild(cell);
table.appendChild(row);
document.getElementById('leaderBoard').appendChild(table);
}
var userCards = ["Card 1", "Card 2", "Card 3"];
var userTotal = 10;
makeTable([userCards, userTotal]);
http://jsfiddle.net/25kg3nnq/

Categories

Resources