Click event for dynamically created button - javascript

I have a function (seen at the very bottom) that creates a HTML table and depending on the contents of an array it will populate it with X number of rows. each row has 2 cells, the value of the array in that position and a button next to it.
I want to be able to click these buttons and delete the particular row from the table.
However, I cant use a standard on click event:
function unMatchButtonClicked(){
var button = document.getElementById('unmatch').onclick;
}
Because it will throw an error that the id does not exist AND because I have potentially X number of rows, I'll need some sort of for loop.
My psuedo attempt is:
for (var i=0; i < table.length; i++){
var button = document.getElementById('unmatch')
if (button.clicked){
remove row}
}
I can't quite vision how to do it though.
Only pure JS solutions as well please, no Jquery.
EDIT :
function makeHTMLMatchesTable(array){
var table = document.createElement('table');
for (var i = 0; i < array.length; i++) {
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.textContent = array[i];
row.appendChild(cell);
cell = document.createElement('td');
var button = document.createElement('button');
button.setAttribute("id", "unMatchButton" +i);
cell.appendChild(button);
row.appendChild(cell);
table.appendChild(row);
}
return table;
}

Add event when you create elements using addEventListener() :
...
var button = document.createElement('button');
button.setAttribute("id", "unMatchButton" +i);
button.addEventListener("click", clickEventFunction, false);
...
Hope this helps.
function makeHTMLMatchesTable(array) {
var table = document.createElement('table');
table.setAttribute("border", 1);
for (var i = 0; i < array.length; i++) {
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.textContent = array[i];
row.appendChild(cell);
cell = document.createElement('td');
var button = document.createElement('button');
button.setAttribute("id", "unMatchButton" + i);
button.textContent = "Delete";
//click Event
button.addEventListener("click", delete_row, false);
cell.appendChild(button);
row.appendChild(cell);
table.appendChild(row);
}
return table;
}
function delete_row() {
this.parentNode.parentNode.remove();
}
document.body.appendChild(makeHTMLMatchesTable(['Cell 1','Cell 2','Cell 3','Cell 4']));

Add a click handler on the <table>. You can then check the event.target if the click has been triggered by a <button>. If yes travel up the DOM until you reach the surrounding <tr> element and call .remove() on it.
function makeHTMLMatchesTable(array) {
var table = document.createElement('table');
for (var i = 0; i < array.length; i++) {
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.textContent = array[i];
row.appendChild(cell);
cell = document.createElement('td');
var button = document.createElement('button');
button.setAttribute("id", "unMatchButton" + i);
button.textContent = "Remove";
cell.appendChild(button);
row.appendChild(cell);
table.appendChild(row);
}
table.addEventListener("click", removeRow, false);
return table;
}
function removeRow(evt) {
if (evt.target.nodeName.toLowerCase() === "button") {
evt.target.parentNode.parentNode.remove(); // .parentNode.parentNode == <tr>
}
}
document.body.appendChild(makeHTMLMatchesTable([1, 2, 3, 4]));

The details are commented within the source. There's a PLUNKER available as well.
<!DOCTYPE html>
<html>
<head>
<style>
table,
td {
border: 1px solid red;
}
button {
height: 24px;
width: 24px;
}
</style>
</head>
<body>
<script>
var array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function makeHTMLMatchesTable(array) {
var table = document.createElement('table');
for (var i = 0; i < array.length; i++) {
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.textContent = array[i];
row.appendChild(cell);
cell = document.createElement('td');
var button = document.createElement('button');
button.setAttribute("id", "unMatchButton" + i);
cell.appendChild(button);
row.appendChild(cell);
table.appendChild(row);
}
// This is added to comlete this function
return document.body.appendChild(table);
}
makeHTMLMatchesTable(array1);
// Reference table
var table = document.querySelector('table');
/*
| - Add an eventListener for ckick events to the table
| - if event.target (element clicked; i.e. button)
| is NOT the event.currentTarget (element that
| is listening for the click; i.e. table)...
| - ...then assign a variable to event.target's
| id (i.e. #unMatchButton+i)
| - Next extract the last char from the id (i.e. from
| #unMatchButton+i, get the 'i')
| - Then convert it into a real number.
| - Determine the row to which the button (i.e. event
| .target) belongs to by using the old rows method.
| - while row still has children elements...
| - ...remove the first child. Repeat until there are
| no longer any children.
| - if the parent of row exists (i.e. table which it
| does of course)...
| - ...then remove row from it's parents
*/
table.addEventListener('click', function(event) {
if (event.target !== event.currentTarget) {
var clicked = event.target.id;
var i = clicked.substr(-1);
var idx = Number(i);
var row = this.rows[idx];
while (row.children > 0) {
row.removeChild(row.firstChild);
}
if (row.parentNode) {
row.parentNode.removeChild(row);
}
return false
}
}, false);
</script>
</body>
</html>

Related

Dynamically created html table data not showing in order as expected

function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "31";
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var thead = document.createElement('td');
thead.classList.add("ui-droppable");
thead.appendChild(data[j]);
tre.appendChild(thead);
tbody.appendChild(tre);
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>
I'm trying to order the data that I get from my server to match the columns of my table.
My table columns are days from Monday to Sunday. When my data has more than 7items it needs to separate with another td. The td shows me week 1 and when my data has more than 7 items it needs to separate again that shows week 2 etc.
Update
Im now using a snipped verdion of my code.
Hope someone can help me out with this.
Thank you
There's a few things going on in the code that are problematic.
An attempt to add the table cells to the row, and the row to the table, was made on each iteration of the for loop. That would have produced a lot of rows with single cells had it worked.
It didn't work because there was only ever a single instance of tre, the row variable. So that meant the line tbody.appendChild(tre); did nothing, since appendChild won't append an element that already has a parent element.
Because your data was an array of references to HTMLElements with parents, appending them using appendChild did nothing for the same reason.
I've amended the code below to take care of all of these situations.
Firstly, the code will append a clone of the data to the cell if it's an HTMLElement. I expect in your real code you won't need this, but for this example, why not? It then appends the cell to the row and continues to the next data element.
Secondly, when the data iterator is at 7, before it appends the "Week N" header, it appends a clone of the row, if it has cells on it.
Finally, after appending the clone of the row, the code will reset the row variable to a new instance of a tr element, with no cells.
I also made some variable name and formatting changes to your code just so I could more easily work with it.
function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "6"; // "31"; Why 31? A week has 7 days...
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
/* Major changes start here */
// if the row has cells
if (tre.querySelectorAll('td').length) {
// clone and append to tbody
tbody.appendChild(tre.cloneNode(true));
// reset table row variable
tre = document.createElement('tr');
}
// then append the Week header
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var td = document.createElement('td');
td.classList.add("ui-droppable");
// Set the value of the cell to a clone of the data, if it's an HTMLElement
// Otherwise, make it a text node.
var value = data[j] instanceof HTMLElement ?
data[j].cloneNode(true) :
document.createTextNode(data[j]);
td.appendChild(value);
tre.appendChild(td);
}
// If the number of data elements is not evenly divisible by 7,
// the remainder will be on the row variable, but not appended
// to the tbody, so do that.
if (tre.querySelectorAll('td').length) {
tbody.appendChild(tre.cloneNode(true));
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>

Trying to find a way to make new columns with JS

I am building a table with JavaScript. If you check the link you can see it is all in one column, but I need the name. prices, and images in separate columns. I am honestly not sure where to start to do this, so I'm looking for some help.
https://jsfiddle.net/wL28gd10/
JS
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto =
["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table"),
row = table.insertRow();
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
// Brreak into next row
var next = i + 1;
if (next%perrow==0 && next!=itemName.length) {
row = table.insertRow();
}
}
// Loop through itemPrice array
for (var i = 0; i < itemPrice.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPrice.length) {
row = table.insertRow();
}
}
// Loop through itemPhoto array
for (var i = 0; i < itemPhoto.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPhoto.length) {
row = table.insertRow();
}
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
Just create all of your columns in one loop, like:
for (var i = 0; i < itemName.length; i++) {
var row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Add cell
cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
You only really need one loop.
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto = ["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table");
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
let row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
table { border-collapse: collapse; }
table tr td {
border: 1px solid black;
padding: 10px;
background-color: white;
}
<div id="menu-table"></div>

Having trouble creating a combo-box using javascript

I need help creating a combo-box in my js file for the timesheet application? So there is an add row button in the timesheet which will create a new Row. I would like to have a drop-down + input for the first column in the row which will list the customers. Initially, there is no row in the timesheet application user will need to add a row to submit the timesheet. After clicking the add row it will create a row in which I would like to have a drop-down in the "Project Code" section which lists Internal Timesheet Application our customers. The JS code I used to create the table is as follows:
var arrHead = new Array(); // array for header.
arrHead = ['', 'Project Code', 'Project Description', 'Billable Hours'];
// first create TABLE structure with the headers.
function createTable() {
var empTable = document.createElement('table');
empTable.setAttribute('id', 'empTable'); // table id.
var tr = empTable.insertRow(-1);
for (var h = 0; h < arrHead.length; h++) {
var th = document.createElement('th'); // create table headers
th.innerHTML = arrHead[h];
tr.appendChild(th);
}
var div = document.getElementById('cont');
div.appendChild(empTable); // add the TABLE to the container.
}
//Creating a drop-downlist for Project Code
// now, add a new to the TABLE.
function addRow() {
var empTab = document.getElementById('empTable');
var rowCnt = empTab.rows.length; // table row count.
var tr = empTab.insertRow(rowCnt); // the table row.
tr = empTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td'); // table definition.
td = tr.insertCell(c);
if (c == 0) { // the first column.
// add a button in every new row in the first column.
var button = document.createElement('input');
// set input attributes.
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
// add button's 'onclick' event.
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
else {
// 2nd, 3rd and 4th column, will have textbox.
var ele = document.createElement('input'); //I would like create a combo-box for 2nd Column
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
}
}
// delete TABLE row function.
function removeRow(oButton) {
var empTab = document.getElementById('empTable');
empTab.deleteRow(oButton.parentNode.parentNode.rowIndex); // button -> td -> tr.
}
// function to extract and submit table data.
function submit() {
var myTab = document.getElementById('empTable');
var arrValues = new Array();
// loop through each row of the table.
for (row = 1; row < myTab.rows.length - 1; row++) {
// loop through each cell in a row.
for (c = 0; c < myTab.rows[row].cells.length; c++) {
var element = myTab.rows.item(row).cells[c];
if (element.childNodes[0].getAttribute('type') == 'text') {
arrValues.push("'" + element.childNodes[0].value + "'");
}
}
}
// The final output.
document.getElementById('output').innerHTML = arrValues;
}
//console.log (arrValues); // you can see the array values in your browsers console window. Thanks :-)
Here is the solution to my Problem:
To make a combo-box for only one column
// now, add a new to the TABLE.
function addRow() {
var empTab = document.getElementById('empTable');
var rowCnt = empTab.rows.length; // table row count.
var tr = empTab.insertRow(rowCnt); // the table row.
tr = empTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td'); // table definition.
td = tr.insertCell(c);
if (c == 0) { // the first column.
// add a button in every new row in the first column.
var button = document.createElement('input');
// set input attributes.
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
// add button's 'onclick' event.
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
**else if (c==1) {**\\ Defining the first column with a drop-down
var values = ["","Tiger", "Dog", "Elephant"];
var select = document.createElement("select");
select.name = "pets";
select.id = "pets";
for (const val of values) {
var option = document.createElement("option");
option.value = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
td.appendChild(select);
}
else{
// 3rd and 4th column, will have textbox.
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
}
}

Get selected row value using javascript

I have dynamically add the table on html button click. Add the teamname,teamid,radio button.
HTML attributes:
<input type="button" value="Generate a table." onclick="generate_table()">
Javascript function :
function generate_table()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
4 rows with 3 columns will generate on the button click , Now i need to get the details on the radio button click.
If i select the radio button from the first row i need to show the teamid in alert box? how can I achieve this in javascript?
try this code below should alert teamid cell's innerText
<input type="button" value="Generate a table." onclick="generate_table()">
function generate_table()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
//here we set value of radio button based on element index and we set a classname for teamid cell
radio.setAttribute("value", i);
cell1.setAttribute("class", "selected_teamid");
//here we add click event
radio.setAttribute("onclick", "getteamid("+i+")");
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
function getteamid(i){
alert(document.getElementsByClassName("selected_teamid")[i].innerText);
}
<input type="button" value="Generate a table." onclick="generate_table()">
just add this line, before appending the radio element:
radio.onclick = function(){alert(this.value};
You just need to add an event handler to the radio button when you create it:
...
radio.addEventListener('click', radioButtonClick, false);
...
function radioButtonClick() {
alert(this.getAttribute('value'));
}
This requires that you set the value of the radio button to your team id, or store it on the radio button (which will be the this inside the event handler) in some other way.
You aren't passing a teamid anywhere, so I assumed the teamid is the index of the looped array.
var generate_table = function()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
radio.setAttribute('data-team', i); // passing the team id
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
// add an event listener on a dynamic element, and alert the team id
document.addEventListener('click', function(e) {
if(e.target && e.target.hasAttribute('data-team')) {
alert(e.target.getAttribute('data-team'));
}
});
You have several way to achieve that:
The easiest way I think is to add an attribute 'teamid' to the radio button. Then just listen for click event and get this value back.
radio.setAttribute('teamid', teamid);
radio.addEventListener('click', onRadioClick);
function onRadioClick(domEvent){
console.log(domEvent.target.getAttribute('teamid'));
}
For me it is not the best way because you need to put some information in the DOM... In my opinion, it would be better to separate the presentation and the data :
var tableData = [
{teamId: 'someId0', title:'title0', someData:'...' },
{teamId: 'someId1', title:'title1', someData:'...' },
{teamId: 'someId2', title:'title2', someData:'...' }
];
for (var i = 0, n = tableData.length ; i < n ; i++){
var rowData = tableData[i];
// Create the row using rowData
// ...
radio.setAttribute('teamid', rowData.teamId);
radio.addEventListener('click', onRadioClick.bind(rowData));
// ...
}
function onRadioClick(domEvent){
// Here this represent data of the row clicked
console.log(this.teamId);
}
I think it's easier to manage because every data are JS side... You don't store any data in the DOM... However both works ;) Hope it helps
radio.setAttribute("onclick", "anotherFunction(this)")
and after this function create anotherFunction():
function anotherFunction(object){
alert(object.parentNode.parentNode.firstChild.innerHTML);
}

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
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() * 12 + 1);
if (j < level) {
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", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// 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()*12+1);
if(j<level)
{
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", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

Categories