How to find out which row was clicked? - javascript

Hello i generate a Table with javascript and now i wont to find out which row and column the user has clicked?
Here are my function for the table:
function doNextSteps() {
removeAustriaFromCountries();
//insert table
var table = document.createElement("table");
table.setAttribute('id', 'matrixTable');
table.setAttribute('class', 'jbiTable');
// insert MATRIX row
var matrixRow = table.insertRow();
var cell = matrixRow.insertCell(); // left column for countries
cell.setAttribute('class', 'jbiMatrixCell');
cell.setAttribute('colSpan', departments.length + 1);
cell.appendChild(document.createTextNode("MATRIX"));
// insert departments row
var departmentsRow = table.insertRow();
var cell = departmentsRow.insertCell(); // left column for countries
cell.setAttribute('class', 'jbiBlankCell');
for (var i = 0; i < departments.length; i++) {
var cell = departmentsRow.insertCell();
cell.appendChild(document.createTextNode(departments[i].name));
cell.setAttribute('class', 'jbiDepartmentCell');
}
for (var i = 0; i < countries.length; i++) {
var countryRow = table.insertRow();
var cell = countryRow.insertCell(); // left country column
//cell.appendChild(document.createTextNode(countries[i].name));
var img = document.createElement('img');
img.src = "example.com + flags[i].name";
cell.appendChild(img);
cell.setAttribute('class', 'jbiCountryCell');
for (var j = 0; j < departments.length; j++) {
var cell = countryRow.insertCell();
var img = document.createElement('img');
img.src = "https://intranet.windkraft.at/OrganisationManual/Documents/Kreis.jpg";
img.onclick = function () {
window.location.href = "example.com" + pdfFiles[i].name;
};
cell.appendChild(img);
cell.setAttribute('class', 'jbiCircleCell');
}
}
$("#divTable").append(table);
}
The table gets generated and now i want to know in which header and in which column the user has clicked. With that information i want to make a new query to get files dynamically displayed in the Table. Any help would be great. And thanks for your Help.

To get the index of the row, you can use this code in your event listener function:
function onClick() {
var cell = this;
var row = cell.parentNode;
var cellIndex = Array.prototype.indexOf.call(row.children, cell);
var rowIndex = Array.prototype.indexOf.call(row.parentNode.children, row);
// do stuff with rowIndex, cellIndex
// rowIndex is the row number starting with row 0
// cellIndex is the column number starting with column 0
}

You can use parentNode.rowIndex & cellIndex to get the cell & rowIndex
document.getElementsByTagName('table')[0].addEventListener('click', function(e) {
console.log(e.target.parentNode.rowIndex,' ',e.target.cellIndex);
}, false);
Check this jsFiddle

Related

How to dynamically add <a> in a html table?

I have a table generated from an array. I'm looking to add a hyperlink to the entire first column of the <tbody> and only the first column.
I am able to add the <a> after the table is created, but then it doesn't actually contain the url within it, it simply appends to what already exists.
Specifically, how can I add a hyperlink to the first column of the
<tbody>?
Generally, as the table is being made, how can I specify different
things (anchors, classes, styles, etc.) for different columns?
http://jsfiddle.net/nateomardavis/n357gqo9/10/
$(function() {
google.script.run.withSuccessHandler(buildTable)
.table();
});
//TABLE MADE USING for
function buildTable(tableArray) {
var table = document.getElementById('table');
var tableBody = document.createElement('tbody');
var tbodyID = tableBody.setAttribute('id', 'tbody');
for (var i = 0; i < tableArray.length; ++i) {
var column = tableArray[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
if (colA != "") {
var row = document.createElement('tr');
var getTbody = document.getElementById('tbody');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column[j]));
row.appendChild(cell);
//NEXT TWO LINES DO NOT WORK
var firstCol = getTbody.rows[i].cells[0];
firstCol.setAttribute('class', 'TEST');
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
/* WORKS AFTER TABLE IS CREATED BUT CAN'T CAPUTRE INTERNAL LINK
var getTbody = document.getElementById('tbody');
for (var i = 0; i < getTbody.rows.length; i++) {
var firstCol = getTbody.rows[i].cells[0]; //first column
//firstCol.style.color = 'red';
//firstCol.setAttribute('class', 'TEST');
var link = document.createElement('a');
firstCol.appendChild(link);
}
*/
}

Dynamically highlight td in a table

Problem
How to highlight dynamically a selected td?
Codepen
Pen here
Code
The map is a 2d array random generated, something like this:
map = [[1,1,1,1,0],
[1,0,0,0,0],
[1,0,1,1,1],
[1,0,0,0,1],
[1,1,1,0,1]]
I can move the player 3 squares per turn and, one of this squares is his actual position. I used this function to call the movement:
function movements(character){
var possibleMovement=3;
let coord=character.actualPosition;
let row = $($("#tableGame tr")[coord.row]);
let cell = $($("td", row)[coord.cell]);
forward(row, cell, possibleMovement, character);
backward(row, cell, possibleMovement, character);
goUp(row, cell, possibleMovement, character);
goDown(row, cell, possibleMovement, character);
};
and with the functions below I try to highlight the cells where the character can actually move.
function forward(row, cell,possibleMovements, character){
for(var i = 0; i<possibleMovements; i++){
cell = $($("td", row)[coord.cell+i]);
var tile = $(".tile", cell).addClass('possibleSteps');
};
};
function backward(row, cell, possibleMovements, character){
for(var i = 0; i>=possibleMovements; i--){
console.log('sei qua');
cell = $($("td", row)[coord.cell+i]);
var tile = $(".tile", cell).addClass('possibleSteps');
};
};
Task
I need to highlight the tiles near the character:
Two tiles above character.actualPosition
Two tiles below
Two tiles at his right
Two tiles at his left
These are the two " testing function "
function forward(row, cell,possibleMovements, character){
for(var i = 0 ; i<possibleMovements; i++){
cell = $($("td", row)[coord.cell +i]);
var tile = $(".tile", cell).addClass('possibleSteps');
console.log([coord.row] + "<<<row" + [coord.cell+i] + "<<<cell");
};
};
function backward(row, cell, possibleMovements, character){
possibleMovements= possibleMovements*-1;
for(var i = 0 ; i>possibleMovements; i--){
cell = $($("td", row)[coord.cell+i]);
var tile = $(".tile", cell).addClass('possibleSteps');
console.log([coord.row] + "<<<row" + [coord.cell-i] + " <<<cell");
};
};
Finally i found an answer. I want to say thanks to this post because it helps me a lot to find a solution that works.
The final functions to highlight the tiles near the character are these
function movements(){
let possibleMovement=3;
let row = character.actualPosition.row;
let cell = character.actualPosition.cell;
forward(possibleMovement, row, cell);
backward(possibleMovement, row, cell);
goUp(possibleMovement, row, cell);
goDown(possibleMovement, row, cell);
};
function forward(possibleMovements, row, cell){
let charRow = row;
let charCell= cell;
var table = $("table")[0];
for(var i = 0; i<possibleMovements; i++){
let cell = table.rows[charRow].cells[charCell+i]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');
};
};
function backward(possibleMovements, row, cell){
let charRow = row;
let charCell= cell;
var table = $("table")[0];
for(var i = -1; i>(possibleMovements*-1); i--){
let cell = table.rows[charRow].cells[charCell+i]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');
};
};
function goUp(possibleMovements, row, cell){
let charRow = row;
let charCell= cell;
var table = $("table")[0];
for(var i = -1; i>(possibleMovements*-1); i--){
let cell = table.rows[charRow+i].cells[charCell]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');
};
};
function goDown(possibleMovements, row, cell){
let charRow = row;
let charCell= cell;
var table = $("table")[0];
for(var i = -1; i<possibleMovements; i++){
let cell = table.rows[charRow+i].cells[charCell]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');
};
};
The main solution was to understand this 4 lines of code, and how i can iterate through them:
var table = $("table")[0];
let cell = table.rows[charRow].cells[charCell+i]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');

How to push values from a dropdown to an array and add the array to a table?

This is the JavaScript. The select has an id of 'counties'.
The table is to be inserted into a div called 'up_bottom'.
var leagueArray = [];
function addTeams() {
var county=document.getElementById("counties");
var val = county.options[county.selectedIndex].value;
leagueArray.push(val);
function display() {
var table = document.createElement("table");
for (var i=0; i<leagueArray.length; i++) {
var row = table.insertRow();
for (var j=0; j<leagueArray[i].length; j++) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(leagueArray[i]));
}
}
var tableDiv = document.getElementById("up_bottom");
tableDiv.appendChild(table);
}
display();
}
Please do the following Steps
Get Selected Value from Dropdown
Put the Selected Value into Array
Create A String of tr element and append it to Table before First tr element
Try this,
function addTeams(){
var leagueArray = [];
var county=document.getElementById("counties");
for (i = 0; i < county.options.length; i++) {
leagueArray[i] = county.options[i].value;
}
display(leagueArray);
}
function display(leagueArray) {
var table = document.createElement("table");
for (var i=0; i<leagueArray.length; i++) {
var row = table.insertRow();
for (var j=0; j<leagueArray[i].length; j++) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(leagueArray[i]));
}
}
var tableDiv = document.getElementById("up_bottom");
tableDiv.appendChild(table);
}
addTeams();

jQuery Add row to table with dynamic ids'

http://jsfiddle.net/waH5S/6/
function add_row_retail() {
$(document).ready(function () {
var table = document.getElementById("Retail");
var row = table.insertRow(-1);
var row_id = $('#Retail').val('tr[id]:last');
console.log(row_id);
var cell_init = row.insertCell(-1);
cell_init.innerHTML = "blank";
});
}
I am trying to get the id of the table row(<tr>) before the added row, and then add 1 to this, with proper parseint(...). Then doing the same with the cell (<td>) next, so that every cell has a unique id for each table. I can't seem to find the row's id.
HERE IS THE "CORRECT" CODE FOR MY QUESTION
function add_row_retail() {
var table = document.getElementById("Retail");
// Row id
var row_id = $('#Retail tr:last').attr('id');
var row = table.insertRow(-1);
var next_row_id = "tr_" + (1+parseInt(row_id.match(/\d+/)[0],10));
$(row).attr('id', next_row_id);
for (var i = 0; i < 8; i++) {
var cell_id = $('#Retail td:last').attr('id');
console.log(cell_id);
var next_cell_id = "td_" + (1+parseInt(cell_id.match(/\d+/)[0],10)); console.log(next_cell_id);
var cell = row.insertCell(-1);
$(cell).attr('id', next_cell_id);
$(cell).innerHTML = "blank";
}
}
Rather than $('#Retail').val('tr[id]:last'); I think you want:
var row_id = $('#Retail tr:last').attr('id')
This selector finds the last tr under the #Retail element, and returns its id attribute.
jQuery last selector: http://api.jquery.com/last-selector/
Next problem: IDs cannot start with numbers. Rename your IDs like "tr_1", "tr_2", etc.
Next problem: To extract the numbers from a string:
"tr_123".match(/\d+/)[0]; // returns 123.
Add 1 to it:
var next_id = "tr_" + (1+parseInt("tr_123".match(/\d+/)[0],10));
Then, set your new id.
var row = table.insertRow(-1);
...
$(row).attr('id', next_id);

MineField with Js

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

Categories

Resources