JavaScript onChange Event to use current row values only - javascript

An extension of my previous calculators, its now time to look at the onChange or addEventListener functions to run my code without using the submit buttons.
I am having a hard time trying to figure out how I can have the event fire once either the 'H' or 'Extra Room Factor' fields have been changed. I only want the row that is being edited / changed to fire the event, not the entire table. I am trying to figure out how I can 'find' which row / cell is calling the function and then use it in the script to get the other values required.
The script uses JSON to get data which determines how the table is set out.
The code should get the values from L, W and H and multiply them together. It should then multiply the Extra Room Factor and write the result into the 'Total Room M3' field.
(No Rep to post images)
Uh, I have all my code in a fiddle but the current code relies on JSON to get the details. I can't post the fiddle link due to low rep!
jsfiddleFiddle Link
JSON File
Thanks!
function init() {
var url = "http://localhost/javascript/comcool/working/data.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.send(null);
request.onload = function () {
if (request.status === 200) {
result = JSON.parse(request.responseText);
drawMainTable();
drawTable2();
drawTable3();
}
rooms = result.numberOfRooms;
};
}
function drawMainTable() {
var div = document.getElementById("calc");
var drawTable = document.createElement("table");
drawTable.id = "calcTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("calcTable");
//Draw Location Field
for ( var i = 0; i < result.locations.length ; i++ ) {
if ( result.locations[i].name !== null) {
var locations = document.getElementById("location");
var option = document.createElement("option");
option.value = result.locations[i].name;
option.text = result.locations[i].name;
locations.appendChild(option);
}
}
//Create Head Elements
for ( var i = 0; i < result.titles.length; i++ ) {
var createHead = document.createElement("th");
createHead.innerHTML = result.titles[i].name;
table.appendChild(createHead);
}
//Create Row Elements
for ( var i = 0; i < result.numberOfRooms ; i++ ) {
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var roomInput = document.createElement("input");
roomInput.type = "text";
roomInput.id = "R" + i + "Name";
cell1.appendChild(roomInput);
var cell2 = row.insertCell(1);
var lInput = document.createElement("input");
lInput.type = "number";
lInput.id = "R" + i + "L";
lInput.className = "smallInput";
cell2.appendChild(lInput);
var cell3 = row.insertCell(2);
var wInput = document.createElement("input");
wInput.type = "number";
wInput.id = "R" + i + "W";
wInput.className = "smallInput";
cell3.appendChild(wInput);
var cell4 = row.insertCell(3);
var hInput = document.createElement("input");
hInput.type = "number";
hInput.id = "R" + i + "H";
hInput.onchange = calculateRoomM3;
hInput.className = "smallInput";
cell4.appendChild(hInput);
var cell5 = row.insertCell(4);
var extraRoomFactorInput = document.createElement("input");
extraRoomFactorInput.type = "number";
extraRoomFactorInput.id = "R" + i + "Factor";
extraRoomFactorInput.value = "1.0";
extraRoomFactorInput.step = "0.1";
extraRoomFactorInput.min = "1.0";
extraRoomFactorInput.max = "1.3";
cell5.appendChild(extraRoomFactorInput);
var cell6 = row.insertCell(5);
var m3Output = document.createElement("output");
m3Output.id = "R" + i + "M3Total";
cell6.appendChild(m3Output);
var cell7 = row.insertCell(6);
var suggDia = document.createElement("output");
suggDia.id = "R" + i + "Dia";
cell7.appendChild(suggDia);
var cell8 = row.insertCell(7);
var outSize = document.createElement("select");
outSize.id = "R" + i + "OutletSize";
cell8.appendChild(outSize);
for ( var x = 0; x < result.ductInfo.length ; x++ ) {
if ( result.ductInfo[x].ventSize != "nil") {
var option = document.createElement("option");
option.value = result.ductInfo[x].ventSize;
option.text = result.ductInfo[x].ventSize;
outSize.appendChild(option);
}
}
var cell9 = row.insertCell(8);
var ductDia = document.createElement("output");
ductDia.id = "R" + i + "DuctSize";
cell9.appendChild(ductDia);
}
}
function drawTable2() {
var p = document.getElementById("total");
var table = document.createElement("Table");
table.id = "totalTable";
table.className = "tg";
p.appendChild(table);
var tableBody = document.createElement('tbody');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++){
var tr = document.createElement('TR');
var outputBox = document.createElement("output");
var inputBox = document.createElement("input");
tableBody.appendChild(tr);
var td = document.createElement('TD');
if ( i === 0 ) {
td.appendChild(document.createTextNode("Total M3 All Rooms:"));
} else if ( i == 1 ) {
td.appendChild(document.createTextNode("Extra House Heat Load:"));
} else if ( i == 2 ) {
td.appendChild(document.createTextNode("Total System m3 Required:"));
}
tr.appendChild(td);
var td = document.createElement('TD');
if ( i === 0 ) {
outputBox.id = "HouseM3Total";
td.appendChild(outputBox);
} else if ( i == 1 ) {
inputBox.type = "number";
inputBox.id = "HouseHeatLoad";
inputBox.value = "1.0";
inputBox.step = "0.1";
inputBox.min = "1.0";
inputBox.max = "1.3";
td.appendChild(inputBox);
} else if ( i == 2 ) {
outputBox.id = "HouseAdjustM3Total";
td.appendChild(outputBox);
}
tr.appendChild(td);
}
}
function drawTable3() {
var div = document.getElementById("dropper");
//create table
var drawTable = document.createElement("table");
drawTable.id = "dropperTable";
drawTable.className = "tg";
div.appendChild(drawTable);
var table = document.getElementById("dropperTable");
//Create Head Elements
for ( var i = 0; i < 3; i++ ) {
var createHead = document.createElement("th");
if ( i === 0) {
createHead.innerHTML = "";
} else if ( i === 1) {
createHead.innerHTML = "Dropper Duct Size";
} else if ( i === 2) {
createHead.innerHTML = "Dropper Duct Capacity";
}
table.appendChild(createHead);
}
for ( var i = 0; i < 6 ; i++ ) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var dropperName = document.createElement("output");
dropperName.innerHTML = "Dropper Duct Side " + [i + 1];
cell1.appendChild(dropperName);
var cell2 = row.insertCell(1);
var dropperInput = document.createElement("input");
dropperInput.type = "number";
dropperInput.id = "D" + [i] + "Size";
cell2.appendChild(dropperInput);
var cell3 = row.insertCell(2);
var dropperOutput = document.createElement("output");
dropperOutput.id = "D" + [i] + "Capacity";
cell3.appendChild(dropperOutput);
}
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var designCapacity = document.createElement("output");
designCapacity.colSpan = "2";
designCapacity.innerHTML = "Design Dropper Capacity";
cell1.colSpan = "2";
cell1.appendChild(designCapacity);
var cell2 = row.insertCell(1);
var DTotalCapacity = document.createElement("output");
DTotalCapacity.id = "DTotalCapacity";
cell2.appendChild(DTotalCapacity);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var modelCapacity = document.createElement("output");
modelCapacity.innerHTML = "Model Dropper Capacity";
cell1.colSpan = "2";
cell1.appendChild(modelCapacity);
var cell2 = row.insertCell(1);
var dropperCapacityUnit = document.createElement("output");
dropperCapacityUnit.id = "dropperCapacityUnit";
cell2.appendChild(dropperCapacityUnit);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var modelSelect = document.createElement("output");
modelSelect.innerHTML = "Model Selection";
cell1.colSpan = "2";
cell1.appendChild(modelSelect);
var cell2 = row.insertCell(1);
var model = document.createElement("output");
model.id = "model";
cell2.appendChild(model);
}
function startCalculate() {
getLocationValue = 0;
totalHouseM3 = 0;
findLocation();
calculateTotalM3();
calculateDuctDia();
findUnitSpecs();
return;
}
function dropperCalculate() {
calculateDropperDia();
finalUnitCalc();
}
function replaceWithDropdownModel( id , valueList ){
var element = document.getElementById( id );
var dropdown = document.createElement("select"),
value = element.value,
option;
dropdown.id = id;
for( var i = 0 ; i < valueList.length ; i++ ){
option = document.createElement("option");
option.text = valueList[i];
option.value = valueList[i];
if( option.value == value){
option.selected = true;
}
dropdown.options.add(option);
}
element.parentNode.replaceChild( dropdown , element );
}
function findLocation() {
var getLocationFactor = document.getElementById("location").value;
for ( var i = 0 ; i < result.locations.length ; i++) {
if (result.locations[i].name === getLocationFactor) {
getLocationValue = result.locations[i].factor;
}
}
}
function calculateTotalM3() {
for ( var i = 0; i < rooms ; i++ ) {
var roomL = document.getElementById("R" + i + "L").value,
roomW = document.getElementById("R" + i + "W").value,
roomH = document.getElementById("R" + i + "H").value,
roomFactor = document.getElementById("R" + i + "Factor").value,
ductDia = document.getElementById("R" + i + "Dia"),
calcM3 = Math.round((roomL * roomW * roomH) * roomFactor);
var outputRoomM3 = document.getElementById("R" + i + "M3Total");
outputRoomM3.innerHTML = calcM3;
totalHouseM3 = totalHouseM3 + calcM3;
var inputHouseHeatLoad = document.getElementById("HouseHeatLoad").value;
var outputHouseM3 = document.getElementById("HouseM3Total");
outputHouseM3.innerHTML = totalHouseM3 + " m3";
for ( var x = 0; x < result.ductInfo.length; x++) {
if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc1 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc1 && getLocationValue === 1) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc2 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc2 && getLocationValue === 2) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc3 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc3 && getLocationValue === 3) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc4 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc4 && getLocationValue === 4) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc5 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc5 && getLocationValue === 5) {
ductDia.innerHTML = result.ductInfo[x].ductSize;
}
}
}
var totalHouseM32 = Math.round(totalHouseM3 * inputHouseHeatLoad);
var outputAdjHouseM3 = document.getElementById("HouseAdjustM3Total");
outputAdjHouseM3.innerHTML = totalHouseM32 + " m3";
}
function calculateDuctDia() {
for ( var i = 0; i < rooms ; i++ ) {
var outletSize = document.getElementById("R" + [i] + "OutletSize").value;
var outputDuctSize = document.getElementById("R" + [i] + "DuctSize");
var diaResult;
for ( var x = 0; x < result.ductInfo.length ; x++) {
if (result.ductInfo[x].ventSize == outletSize) {
diaResult = result.ductInfo[x].ventSize;
}
}
outputDuctSize.innerHTML = diaResult;
}
}
function findUnitSpecs() {
unitArray = [];
for ( var x = 0 ; x < result.modelFinder.length; x++) {
if (totalHouseM3 <= result.modelFinder[x].location1Capacity && getLocationValue === 1) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location2Capacity && getLocationValue === 2) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location3Capacity && getLocationValue === 3) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location4Capacity && getLocationValue === 4) {
unitArray.push(result.modelFinder[x].model);
} else if (totalHouseM3 <= result.modelFinder[x].location5Capacity && getLocationValue === 5) {
unitArray.push(result.modelFinder[x].model);
}
replaceWithDropdownModel( "model" , unitArray);
}
return [
unitArray
];
}
function calculateDropperDia() {
totalDropperCapacity = 0;
dropperSides = 6;
for ( var i = 0; i < dropperSides ; i++ ) {
var dropperSize = document.getElementById("D" + i + "Size").value,
outputDropperCapacity = document.getElementById("D" + i + "Capacity");
var dropperResult;
for ( var x = 0; x < result.ductInfo.length ; x++) {
if (result.ductInfo[x].ductSize == dropperSize) {
dropperResult = result.ductInfo[x].dropperCapacity;
} else if (dropperSize > 551) {
dropperResult = "Size Does Not Exist";
}
}
outputDropperCapacity.innerHTML = dropperResult;
var dropperCapacityElement = document.getElementById("DTotalCapacity");
totalDropperCapacity = totalDropperCapacity + dropperResult;
dropperCapacityElement.innerHTML = totalDropperCapacity;
}
}
function finalUnitCalc() {
var selectedUnit = document.getElementById("model").value,
dropperCapacityUnit = document.getElementById("dropperCapacityUnit");
for ( var i = 0 ; i < result.modelFinder.length ; i++) {
if (selectedUnit === result.modelFinder[i].model) {
dropperCapacityUnit.innerHTML = result.modelFinder[i].dropperCapacity;
}
}
}
window.onload = init;
function calculateRoomM3() {
// iterate through all current rows and get the values of each, save it as a variable in each and then calculate
//
var table = document.getElementById("calcTable");
var rowCount = table.rows[0].cells[1].childNodes[0].value;
console.log(rowCount);
// var roomL =
// roomW =
// roomH =
// roomFactor =
// roomTotal =
// var thisID = document.getElementById(thisID).value,
//thisW = document.getElementById(thisW).value,
//thisL = document.getElementById(thisL).value,
//thisFactor = document.getElementById(thisFactor).value,
//thisTotal = document.getElementById(thisTotal);
//var roomM3 = Math.round((thisL * thisW * thisID)) * thisFactor;
//thisTotal.innerHTML = roomM3;
//console.log(thisID);
//console.log(thisW);
//console.log(thisL);
//console.log(roomM3);
}
#calc{
width: 850px;
margin-bottom: 1em;
}
div {
border: 1px solid white;
}
#dropper {
width: 400px;
position: absolute;
margin-left: 875px;
}
#total {
clear: both;
}
#button2 {
position:absolute;
margin-left: 875px;
margin-top: -250px;
}
h1 {
text-align: center;
}
p {
text-align: center;
}
input {
text-align: center;
}
.tg {
border-collapse:collapse;
border-spacing:0;
text-align: center;
}
.tg td{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
}
.tg th{
font-family:Arial, sans-serif;
font-size:14px;
font-weight:normal;
padding:10px 5px;
border-style:solid;
border-width:1px;
overflow:hidden;
word-break:normal;
text-align: center;
vertical-align: top;
}
.tg .tg-s6z2{
text-align:center
}
.smallInput {
width: 50px;
text-align: center;
}
.factors {
text-align: center;
width: 80px;
}
.factors2 {
text-align: center;
width: 150px;
}
.tg2 {
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: none;
border-top-color: #FFF;
border-right-color: #FFF;
border-bottom-color: #FFF;
border-left-color: #FFF;
}
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="ComCool.js" type="text/javascript"></script>
<meta charset="utf-8">
</head>
<body>
<form>
<div id="dropper">
<h1>Dropper Duct Calculator</h1><br>
<br>
</div>
<div id="calc">
<h1>Calculator</h1>
<p>Location: <select id="location">
</select></p>
</div>
</form>
<div id="total"></div>
<br/>
<div id="button2">
<input onclick="startCalculate()" type="button" value=
"1. Calculate M3, Diameter (Suggested and Actual)">
<br/></br>
<input onclick="dropperCalculate()" type="button" value=
"2. Calculate Dropper"><br>
</div>
<br>
</body>
</html>

I solved this for now by getting the entire ID of the current cell the event runs from, then splicing to get the ID scheme that I have through the table.
var str = this.id,
slice = str.slice(0,2),
roomL = slice + "L",
roomW = slice + "W",
roomH = slice + "H",
roomFactor = slice + "Factor",
roomTotal = slice + "M3Total",
roomDuctDia = slice + "Dia",
Its a quick solve, but it works!

Related

Changing a <td> while selected, and reverting the changes after a different <td> is selected?

I am building a table and I want the background color of the selected cell to change. Then when i select a different cell (and apply the same change to this new cell), I want the change to revert in the first (no longer selected) cell. What is the best approach to this? Here is my code:
var table = '';
for (var r = 0; r < rows; r++) {
table += '<tr>';
for (var c = 0; c < cols; c++) {
if (c == 0) {
if (r == 0) {
var cellID = r.toString();
cellID += letterArray[c - 1];
table += '<td style="min-width:50px; height:25px;">' + '</td>';
}
else {
var cellID = r.toString();
cellID += letterArray[c - 1];
table += '<td style="min-width:50px; height:25px">' + r + '</td>';
}
}
else if (r == 0 && c > 0) {
var cellID = r.toString();
cellID += letterArray[c - 1];
table += '<td style="min-width:50px; height:25px">' + letterArray[c - 1] + '</td>';
}
else {
var cellID = r.toString();
cellID += letterArray[c - 1];
table += '<td id="' + cellID + '" style="min-width:50px; height:25px;" onclick="selectCell(this)">' + '</td>';
}
}
table += '</tr>';
}
Writing the table to the document:
document.write('<table id="table" border=1>' + table + '</table>');
selectCell function:
function selectCell(x) {
alert("Row = " + x.parentNode.rowIndex + " Col = " + String.fromCharCode((x.cellIndex - 1) + 65));
x.style.backgroundColor = 'purple';
}
This is where i encounter my problem. As I click the first cell, my alert shows me the info of which cell i have selected, and then changes the background color. Then when i select a different cell, it alerts me with the new cell row and column info, and changes the color.
What is the best way to revert the color change of the previously selected cell?
Thank you for your time and energy!
You should make a CSS class that applies the background color and add/remove it in your function. Your function can check for an element that already has the class, like this:
CSS:
.selected {
background-color: purple;
}
JS:
function selectCell(x) {
var currentSelection = document.querySelector('.selected');
if (currentSelection) {
currentSelection.classList.remove('selected');
}
x.classList.add('selected');
}
I agree with #Rishat Muhametshin that you should avoid using document.write. And I liked how #skyline3000 solved it so I put everything together into a snippet for you to see a cleaner way to code this.
I even went so far as to give you true headers on the top and the side and then added extra CSS to make them look more like headers.
var rows = 7;
var cols = 8;
var table = document.createElement('table');
var selecedTd;
table.id = "table";
table.border = 1;
table.cellSpacing = 0;
table.cellPadding = 4;
document.body.appendChild(table);
for (var r = 0; r < rows; r++) {
var tr = document.createElement('tr');
if (r > 0) {
tr.id = "row"+r;
}
table.appendChild(tr);
for (var c = 0; c < cols; c++) {
var cell;
var char = String.fromCharCode(c+64);
if (c===0 || r===0) {
cell = document.createElement('th');
cell.setAttribute('style', 'min-width:50px; height:25px;');
} else {
cell = document.createElement('td');
}
tr.appendChild(cell);
if (c == 0 && r > 0) {
cell.textContent = r;
}
else if (r == 0) {
if (c > 0) {
cell.textContent = char
cell.id = "col"+c;
}
}
else {
cell.id = r+char;
cell.addEventListener('click', selectCell);
//cell.textContent = cell.id;
}
}
}
function selectCell(event) {
var x = event.target;
var currentSelection = document.querySelector('.selected');
if (currentSelection) {
currentSelection.classList.remove('selected');
}
x.classList.add('selected');
}
.selected {
background-color: purple;
color: white;
}
th {
background-color: #DDD;
}
td {
cursor: pointer;
}
UPDATE
Below is code that will allow editing of the selected field. It needs work before it could be used in production and you would want to save the data in some array or object as well as in the cells, but it should get you going.
var rows = 7;
var cols = 8;
var table = document.createElement('table');
var selecedTd;
var inputField = document.createElement('input');
table.id = "table";
table.border = 1;
table.cellSpacing = 0;
table.cellPadding = 4;
document.body.appendChild(table);
inputField.className = "roving-input";
for (var r = 0; r < rows; r++) {
var tr = document.createElement('tr');
if (r > 0) {
tr.id = "row"+r;
}
table.appendChild(tr);
for (var c = 0; c < cols; c++) {
var cell;
var char = String.fromCharCode(c+64);
if (c===0 || r===0) {
cell = document.createElement('th');
} else {
cell = document.createElement('td');
}
tr.appendChild(cell);
if (c == 0 && r > 0) {
cell.textContent = r;
}
else if (r == 0) {
if (c > 0) {
cell.textContent = char
cell.id = "col"+c;
}
}
else {
cell.id = r+char;
cell.addEventListener('click', selectCell);
cell.textContent = cell.id;
}
}
}
function selectCell(event) {
var x = event.target;
var currentSelection = document.querySelector('.selected');
if (x !== currentSelection && x.localName === 'td') {
if (currentSelection) {
currentSelection.textContent = inputField.value;
currentSelection.classList.remove('selected');
}
x.classList.add('selected');
inputField.value = x.textContent;
x.appendChild(inputField);
inputField.style.width = (x.clientWidth-2)+'px';
inputField.focus();
inputField.select();
}
}
.selected {
position: relative;
}
th {
background-color: #DDD;
height:25px;
min-width:50px;
}
td {
cursor: pointer;
}
.roving-input {
background-color: #FDF;
border: none;
bottom: 0;
display: inline-block;
left: 0;
outline: none;
position:absolute;
right: 0;
top: 0;
}

Saving two sets of coordinates using event Click Handlers

What I've done: So I am creating a game of chess in Java Script, and I have an 8 by 8 board (html table) with pieces on the board. I have currently set up some Click Handlers to recognize what board spot the user has clicked on (each td has its own id 0-63, and using this.cellIndex and .rowIndex I can get the coordinates).
Problem: My code so far is working but I'm currently trying to figure out how to save two separate user inputs (one selecting the coordinates of the where the piece currently is, and the second where the user wants the piece to go). My idea was to pass the variable cellContent as a parameter from "selectPiece()" to "movePiece()" so that I could have both variables in the same funciton but I can't seem to get it to work. Any suggestions or other ideas?
My Code:
function addClickHandlers() {
var cells = document.getElementsByTagName("td");
for (var i = 0; i< cells.length; i++) {
cells[i].onclick = function selectPiece() {
var coordinates = document.getElementById("coordinates");
var col = this.cellIndex
var row = this.parentNode.rowIndex;
var thisCell = this.id;
var cellContent = document.getElementById(thisCell).innerHTML;
document.getElementById(this.id).style.backgroundColor = "blue";
var cells = document.getElementsByTagName("td");
for (var i = 0; i< cells.length; i++) {
cells[i].onclick = function movePiece() {
var coordinates = document.getElementById("coordinates");
var col = this.cellIndex
console.log(this.cellIndex);
var row = this.parentNode.rowIndex;
console.log(this.id);
var thisCell = this.id;
var cellContent = document.getElementById(thisCell).innerHTML;
console.log(cellContent);
document.getElementById(this.id).style.backgroundColor = "red";
};
}
var postCoordinates = document.createTextNode("You clicked on coordinates: (" + row + "," + col + ").");
coordinates.appendChild(postCoordinates);
var br = document.createElement("br");
coordinates.appendChild(br);
};
}
}
Snippet
function showBoard() {
var tr;
var td;
var check;
var i = 0;
var j = 0;
var cellId = 0;
var table = document.getElementById("myTable");
for(i = 0; i < 8; i++) {
tr = table.insertRow(i);
for(j = 0; j < 8; j++) {
td = tr.insertCell(j);
if(i%2 == 1)
{
if(j%2 == 1)
{
td.setAttribute("class", "black");
}
else
{
td.setAttribute("class", "white");
}
}
else
{
if(j%2 == 1)
{
td.setAttribute("class", "white");
}
else
{
td.setAttribute("class", "black");
}
}
cellId = (i * 8) + j;
td.setAttribute("id", cellId);
var content = getSquare(i, j);
if (content == "br") {
var blackRook = document.createElement("IMG");
blackRook.setAttribute("src", "chess-piece-black-rook.png");
td.appendChild(blackRook);
}
else if (content == "bk") {
var blackKnight = document.createElement("IMG");
blackKnight.setAttribute("src", "chess-piece-black-knight.png");
td.appendChild(blackKnight);
}
else if (content == "bb") {
var blackBishop = document.createElement("IMG");
blackBishop.setAttribute("src", "chess-piece-black-bishop.png");
td.appendChild(blackBishop);
}
else if (content == "bK") {
var blackKing = document.createElement("IMG");
blackKing.setAttribute("src", "chess-piece-black-king.png");
td.appendChild(blackKing);
}
else if (content == "bQ") {
var blackQueen = document.createElement("IMG");
blackQueen.setAttribute("src", "chess-piece-black-queen.png");
td.appendChild(blackQueen);
}
else if (content == "bp") {
var blackPawn = document.createElement("IMG");
blackPawn.setAttribute("src", "chess-piece-black-pawn.png");
td.appendChild(blackPawn);
}
else if (content == "wr") {
var whiteRook = document.createElement("IMG");
whiteRook.setAttribute("src", "chess-piece-white-rook.png");
td.appendChild(whiteRook);
}
else if (content == "wk") {
var whiteKnight = document.createElement("IMG");
whiteKnight.setAttribute("src", "chess-piece-white-knight.png");
td.appendChild(whiteKnight);
}
else if (content == "wb") {
var whiteBishop = document.createElement("IMG");
whiteBishop.setAttribute("src", "chess-piece-white-bishop.png");
td.appendChild(whiteBishop);
}
else if (content == "wK") {
var whiteKing = document.createElement("IMG");
whiteKing.setAttribute("src", "chess-piece-white-king.png");
td.appendChild(whiteKing);
}
else if (content == "wQ") {
var whiteQueen = document.createElement("IMG");
whiteQueen.setAttribute("src", "chess-piece-white-queen.png");
whiteQueen.setAttribute("id", "botImg");
td.appendChild(whiteQueen);
}
else if (content == "wp") {
var whitePawn = document.createElement("IMG");
whitePawn.setAttribute("src", "chess-piece-white-pawn.png");
td.appendChild(whitePawn);
}
}
}
addClickHandlers();
}
function addClickHandlers() {
var cells = document.getElementsByTagName("td");
for (var i = 0; i< cells.length; i++) {
cells[i].onclick = function selectPiece() {
var coordinates = document.getElementById("coordinates");
var col = this.cellIndex
console.log(this.cellIndex);
var row = this.parentNode.rowIndex;
console.log(this.id);
var thisCell = this.id;
var cellContent = document.getElementById(thisCell).innerHTML;
console.log(cellContent);
document.getElementById(this.id).style.backgroundColor = "blue";
var cells = document.getElementsByTagName("td");
for (var i = 0; i< cells.length; i++) {
cells[i].onclick = function movePiece() {
var coordinates = document.getElementById("coordinates");
var col = this.cellIndex
console.log(this.cellIndex);
var row = this.parentNode.rowIndex;
console.log(this.id);
var thisCell = this.id;
var cellContent = document.getElementById(thisCell).innerHTML;
console.log(cellContent);
document.getElementById(this.id).style.backgroundColor = "red";
};
}
var postCoordinates = document.createTextNode("You clicked on coordinates: (" + row + "," + col + ").");
coordinates.appendChild(postCoordinates);
var br = document.createElement("br");
coordinates.appendChild(br);
};
}
}
//Game state variables
var grid = [[ "br", "bk", "bb", "bK", "bQ", "bb", "bk", "br" ],
[ "bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp" ],
[ " ", " ", " ", " ", " ", " ", " ", " " ],
[ " ", " ", " ", " ", " ", " ", " ", " " ],
[ " ", " ", " ", " ", " ", " ", " ", " " ],
[ " ", " ", " ", " ", " ", " ", " ", " " ],
[ "wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp" ],
[ "wr", "wk", "wb", "wK", "wQ", "wb", "wk", "wr" ]];
var turn = 7;
var capturedWhite = [];
var capturedBlack = ["bp"];
var gameOver = false;
//Game state functions
function getSquare(row, col) {
return grid[row][col];
}
function pawnMove(start, finish)
{
}
table {
background-color: black;
}
td.white {
height: 65px;
width: 65px;
background-color: white;
}
td.black {
height: 65px;
width: 65px;
background-color: black;
hover {
background-color: white;
}
}
img {
height: 45px;
width: 45px;
padding: 10px;
}
td:hover {
background-color: blue;
}
body {background: #cba;}
#botDiv {position: relative; bottom: 0; left: 0; height: 65;}
#botImg {position: relative; bottom: 0; left: 0;}
<!DOCTYPE html>
<html>
<head>
<title>Game Grid</title>
<link rel="stylesheet" href="gameGridStyle.css">
</head>
<body onload="showBoard();">
<div id="botDiv">
</div>
<script src = "genTable.js"></script>
<script src = "model.js"></script>
<script src = "queenBot.js"></script>
<script src = "loadGame.js"></script>
<table id="myTable">
</table>
<p id="coordinates">
</p>
<label>Here is your user data: </label>
<div id="username"></div><br>
<div id="timestamp"></div>
<button id="logoutButton" onclick="logout()">Log-out</button><br><hr>
<div id="loadDataDiv"></div>
<button id="loadGame" onclick="loadData()">Load Game</button><br><hr>
</body>
</html>

Add onclick event to individual divs within loop

I am making a tic-tac-toe game.
I would like to add individual onclick event to each div so I can add either an "X" or an "O" depending on the div I click. "O" will be added later.
JavaScript:
function createDivs() {
for (i = 0; i < 9; i++) {
var d = document.createElement("DIV");
document.body.appendChild(d);
//Stuck here -borrowed some of this from a similar topic-
d.onclick = function() {
return function() {
var p = document.createElement("P");
var x = document.createTextNode("X");
p.appendChild(x);
d.appendChild(p);
}
}(i);
//-------------------------------------------------
var ii = document.createAttribute("id");
ii.value = "D" + i;
d.setAttributeNode(ii);
var z = "D" + i;
if (i == 3 || i == 6) {
document.getElementById(z).style.clear = "left";
}
}
}
html: <body onload="createDivs()">
Pass d as argument and accept it as argument so that closure will remember it when click handler-function will be executed.
d is nothing but the element you are creating(var d = document.createElement("DIV");)
function createDivs() {
for (i = 0; i < 9; i++) {
var d = document.createElement("DIV");
d.style.float = 'left';
document.body.appendChild(d);
d.onclick = function(d) {
//----------------^^^ Accept d here
return function() {
var p = document.createElement("P");
var x = document.createTextNode("X");
p.appendChild(x);
d.appendChild(p);
d.onclick = function() {}; //Unset function after click event
}
}(d);
//^^ Pass d here
var ii = document.createAttribute("id");
ii.value = "D" + i;
d.setAttributeNode(ii);
var z = "D" + i;
if (i == 3 || i == 6) {
document.getElementById(z).style.clear = "left";
}
}
}
div {
width: 30px;
height: 30px;
border: 1px solid black;
}
<body onload="createDivs()">
Update: As suggested by Barmar in comments, value of this in the event-handler function will be the element on which event registered.
function createDivs() {
for (i = 0; i < 9; i++) {
var d = document.createElement("DIV");
d.style.float = 'left';
document.body.appendChild(d);
d.onclick = function() {
var p = document.createElement("P");
var x = document.createTextNode("X");
p.appendChild(x);
this.appendChild(p);
this.onclick = function() {}; //Unset function after click event
};
var ii = document.createAttribute("id");
ii.value = "D" + i;
d.setAttributeNode(ii);
var z = "D" + i;
if (i == 3 || i == 6) {
document.getElementById(z).style.clear = "left";
}
}
}
div {
width: 30px;
height: 30px;
border: 1px solid black;
}
<body onload="createDivs()">

How do I change an HTML table cell value by a dynamically added button in each row

var insert = document.getElementById('insertitem');
insert.addEventListener('click', function() {
var table = document.getElementById('insertfirsttable'),
itemType = prompt("Enter the Item type"),
filling1 = prompt("Enter the filling"),
filling2 = prompt("Enter the filling"),
filling3 = prompt("Enter the filling"),
stock = prompt("Enter the amount in stock"),
minimum_Stock = prompt("Enter the stock minimum");
for (var r = 0; r < 1; r += 1) {
var x = document.getElementById('insertfirsttable').insertRow(r);
for (var c = 0; c < 10; c += 1) {
var y = x.insertCell(c);
}
table.rows[r].cells[0].innerHTML = itemType;
table.rows[r].cells[1].innerHTML = filling1;
table.rows[r].cells[2].innerHTML = filling2;
table.rows[r].cells[3].innerHTML = filling3;
table.rows[r].cells[4].innerHTML = stock;
table.rows[r].cells[5].innerHTML = minimum_Stock;
table.rows[r].cells[9].style.width = "100px";
var CreateBtn = document.createElement("button");
CreateBtn.innerHTML = "sell";
CreateBtn.id = "sellbtn";
CreateBtn.style.width = "100px";
CreateBtn.style.height = "25px";
CreateBtn.style.cursor = "pointer";
CreateBtn.style.fontSize = "18px";
table.rows[r].cells[9].appendChild(CreateBtn);
var sellBtn = document.getElementById("sellbtn");
CreateBtn.onclick = function Sell() {
var sell = prompt("Enter the amount of stock you're selling");
for (var a = 0; a < table.length; a += 1) {
for (var b = 0; b < table.cells.length; b += 1) {
}
}
table.rows[a].cells[4].innerHTML = parseInt(table.rows[a].cells[4].innerHTML) - sell;
}
}
});
body {
margin: 0;
padding: 0;
background-color: #E6E6E6;
font-size: 20px;
}
table {
border-spacing: 1px;
width: 100%;
}
th {
padding: 1px;
}
#firsttablediv {
width: 100%;
}
#firsttable {
color: white;
background-color: green;
}
#insertitem {
width: 100%;
padding: 2px;
font-size: 20px;
cursor: pointer;
}
#insertfirsttable > tr {
background-color: #31B404;
}
<html>
<body>
<div id="firsttablediv">
<table id="firsttable" border="1">
<thead>
<th>Item Type</th>
<th colspan="3">Filling</th>
<th>Stock</th>
<th>Stock Minimum</th>
<th>Closing Inventory</th>
<th>Sell</th>
<th>Last Month Inventory</th>
<th colspan="2">
<button id="insertitem">New Item</button>
</th>
</thead>
<tbody id="insertfirsttable">
</tbody>
</table>
</div>
</body>
</html>
When I press on the sell button (which is dynamically added by JavaScript to each row when an item is added)
I want it to ask me about the amount I want to sell of that item and then when I enter the amount it should subtract the stock amount from the amount I want to sell (the one entered previously) and then update the stock amount in the cell of that item's row to the new number.
It's pretty simple but I just can't figure it out.
Change this line:
table.rows[a].cells[4].innerHTML = parseInt(table.rows[a].cells[4].innerHTML) - sell;
to this line:
this.parentNode.parentNode.cells[4].innerHTML = parseInt(this.parentNode.parentNode.cells[4].innerHTML) - sell;
To do it like you're trying, you would have to use a closure. This way, when you click a button, it adjusts the value of the button's parent's (td) parent (tr) cell 4.
Is that what you want? (fiddle)
var insert = document.getElementById('insertitem');
insert.addEventListener('click', function() {
var table = document.getElementById('insertfirsttable'),
itemType = prompt("Enter the Item type"),
filling1 = prompt("Enter the filling"),
filling2 = prompt("Enter the filling"),
filling3 = prompt("Enter the filling"),
stock = prompt("Enter the amount in stock"),
minimum_Stock = prompt("Enter the stock minimum");
for (var r = 0; r < 1; r += 1) {
var x = document.getElementById('insertfirsttable').insertRow(r);
for (var c = 0; c < 10; c += 1) {
var y = x.insertCell(c);
}
table.rows[r].cells[0].innerHTML = itemType;
table.rows[r].cells[1].innerHTML = filling1;
table.rows[r].cells[2].innerHTML = filling2;
table.rows[r].cells[3].innerHTML = filling3;
table.rows[r].cells[4].innerHTML = stock;
table.rows[r].cells[5].innerHTML = minimum_Stock;
table.rows[r].cells[9].style.width = "100px";
var CreateBtn = document.createElement("button");
CreateBtn.innerHTML = "sell";
CreateBtn.id = "sellbtn";
CreateBtn.style.width = "100px";
CreateBtn.style.height = "25px";
CreateBtn.style.cursor = "pointer";
CreateBtn.style.fontSize = "18px";
table.rows[r].cells[9].appendChild(CreateBtn);
var sellBtn = document.getElementById("sellbtn");
CreateBtn.onclick = function Sell() {
var sell = prompt("Enter the amount of stock you're selling");
for (var a = 0; a < table.length; a += 1) {
for (var b = 0; b < table.cells.length; b += 1) {
}
}
table.rows[a].cells[4].innerHTML = parseInt(table.rows[a].cells[4].innerHTML) - sell;
table.rows[a].cells[7].innerHTML = (parseInt(table.rows[a].cells[7].innerHTML)) ? parseInt(table.rows[a].cells[7].innerHTML) + parseInt(sell) : sell;
}
}
});
body {
margin: 0;
padding: 0;
background-color: #E6E6E6;
font-size: 20px;
}
table {
border-spacing: 1px;
width: 100%;
}
th {
padding: 1px;
}
#firsttablediv {
width: 100%;
}
#firsttable {
color: white;
background-color: green;
}
#insertitem {
width: 100%;
padding: 2px;
font-size: 20px;
cursor: pointer;
}
#insertfirsttable > tr {
background-color: #31B404;
}
<html>
<body>
<div id="firsttablediv">
<table id="firsttable" border="1">
<thead>
<th>Item Type</th>
<th colspan="3">Filling</th>
<th>Stock</th>
<th>Stock Minimum</th>
<th>Closing Inventory</th>
<th>Sell</th>
<th>Last Month Inventory</th>
<th colspan="2">
<button id="insertitem">New Item</button>
</th>
</thead>
<tbody id="insertfirsttable">
</tbody>
</table>
</div>
</body>
</html>
var rowCount =0; // add a counter for your row
var insert = document.getElementById('insertitem');
insert.addEventListener('click', function() {
rowCount++; // increase row counter
var table = document.getElementById('insertfirsttable'),
itemType = prompt("Enter the Item type"),
filling1 = prompt("Enter the filling"),
filling2 = prompt("Enter the filling"),
filling3 = prompt("Enter the filling"),
stock = prompt("Enter the amount in stock"),
minimum_Stock = prompt("Enter the stock minimum");
for (var r = 0; r < 1; r += 1) {
var x = document.getElementById('insertfirsttable').insertRow(r);
for (var c = 0; c < 10; c += 1) {
var y = x.insertCell(c);
}
table.rows[r].cells[0].innerHTML = itemType;
table.rows[r].cells[1].innerHTML = filling1;
table.rows[r].cells[2].innerHTML = filling2;
table.rows[r].cells[3].innerHTML = filling3;
table.rows[r].cells[4].innerHTML = stock;
table.rows[r].cells[4].id = "stock_"+rowCount; // add an id to your cell
table.rows[r].cells[5].innerHTML = minimum_Stock;
table.rows[r].cells[7].id = "sell_"+rowCount;
table.rows[r].cells[7].innerHTML = "0";
table.rows[r].cells[9].style.width = "100px";
var CreateBtn = document.createElement("button");
CreateBtn.innerHTML = "sell";
CreateBtn.id = "sellbtn";
CreateBtn.title = rowCount; // add title to your button to have the row counter
CreateBtn.style.width = "100px";
CreateBtn.style.height = "25px";
CreateBtn.style.cursor = "pointer";
CreateBtn.style.fontSize = "18px";
table.rows[r].cells[9].appendChild(CreateBtn);
var sellBtn = document.getElementById("sellbtn");
CreateBtn.onclick = function Sell() {
var sell = prompt("Enter the amount of stock you're selling");
stock_cell = document.getElementById("stock_"+this.title); // find the stock cell with row counter
sell_cell = document.getElementById("sell_"+this.title);
stock_item = parseInt(stock_cell.innerHTML); // get the current value
sell_item = parseInt(sell_cell.innerHTML);
stock_cell.innerHTML = stock_item - parseInt(sell); // increase sell item from stock
sell_cell.innerHTML = sell_item + parseInt(sell);
}
}

passing parameter dynamically in javascript to a button event

I have a function that addRow to a table
function addRow(tableId,rowEle)
{
var tab = document.getElementById(tableId);
var hrow = tab.insertRow();
var func = null;
for (var j = 0; j < rowEle.length; j++) {
var newTD = document.createElement("TD");
var elem = document.createElement(rowEle[j].desc);
elem.type = rowEle[j].type;
elem.type == "button" ? elem.value = rowEle[j].label : false;
rowEle[j].action != undefined ? elem.setAttribute(rowEle[j].action[0],rowEle[j].action[1]): false;
elem.style = rowEle[j].cssStyle;
newTD.appendChild(elem);
hrow.appendChild(newTD);
}
}
and my declaration looks like this
var eobject = new Object();
eobject.desc = "input";
eobject.type = "button";
eobject.label = "+";
eobject.action = new Array("onclick","addRow('tbl1',eleme)");
eobject.cssStyle = "width : 100%; border: 0px none; background-color:lightgreen;";
eleme.push(eobject);
** My Working Solution **
Thanks everyone for your help.

Categories