I am implemented successfully the recursive table. Then I added the (click) method in the parent tr in order to call the child method to fetch data from database to display in the child tr.the problem is i am able to get the data in the child. but the child tr immediately appear and disappear.Could you please anyone help me on this to display the child tr when i click the parent tr.
sampletree() {
var = ele < HTMLTableElement > document.getElementById("tableid");
ele.addEventListener("click", (ev: MouseEvent) => {
var element = ev.target as HTMLElement;
if (element.tagName !== "A")
return false;
ev.preventDefault();
var row = element.closest("tr");
var cls = row.classList[0];
var lvl = +(cls.slice(-1)) + 1;
cls = cls.slice(0, -1) + lvl;
while ((row = nextTr(row)) && (row.className.includes(cls) || row.className.includes("open")))
row.classList.toggle("open");
});
function nextTr(row) {
while ((row = row.nextSibling) && row.nodeType != 1);
return row;
}
}
getTableParent1(): void {
this.service.getTableParent1()
.subscribe(TableParent1 => this.TableParent1 = TableParent1;
}
getChild(): void {
this.service.getTablechild1()
.subscribe(Tablechild1 => this.Tablechild1 = Tablechild11;
}
ngOnInit() {
this.TableParent1();
this.sampletree();
}
tbody>tr {
display: none;
}
/* Simplified */
tr.level0,
tr.open {
display: table-row;
}
/* Added colors for better visibility */
/* Added some more styling after comment */
tr td {
padding: 0.2em 0.4em;
}
tr td:first-of-type {
position: relative;
padding: 0.2em 1em;
}
tr td a {
color: #0e879a;
text-decoration: inherit;
position: relative;
left: -0.73em;
font-size: 19px;
}
tr.level1 td:first-of-type {
padding-left: 1.5em;
}
tr.level2 td:first-of-type {
padding-left: 2em;
}
<table class="table table-bordered table-hover" id="tableid">
<thead>
<tr>
<th>test1</th>
<th>test2</th>
</tr>
</thead>
<tbody>
<tr class="level0" *ngFor="let tavles of tables">
<td>+{{tavles.test2}}</td>
<td>{{tavles.test1}}</td>
</tr>
<tr class="level1" *ngFor="let child of tablechild">
<td>+{{child.test1}}</td>
<td>+{{child.test2}} </td>
</tr>
Related
I am currently trying to add a feature where when I click the name of a user in the table it will display all of the posts made by that User however I am completely stumped. The url for the posts is https://jsonplaceholder.typicode.com/posts
I currently have the table set up and will attach images of the table and code below.
Here is the problem I am trying to solve for further context
Using jQuery or vanilla JS you will display each USER in a table. When the user selects a USER in the table, it will display all of the 'POSTS' that were created by that USER.
Make use of event delegation together with Element.closest and the data-* attribute respectively its HTMLElement.dataset counterpart.
document
.querySelector('tbody')
.addEventListener('click', ({ target }) => {
const currentRow = target.closest('tr');
const userId = currentRow.dataset.id;
console.clear();
console.log('userId: ', userId);
});
body {
margin: 0 0 0 2px;
}
table {
border-collapse: collapse;
}
thead th {
color: #fff;
font-weight: bolder;
background-color: #009577;
}
th, td {
padding: 4px 10px 6px 10px;
color: #0a0a0a;
}
tbody tr:nth-child(even) {
background-color: #eee;
}
tbody tr:hover {
outline: 2px dotted orange;
}
tbody tr {
cursor: pointer;
}
tbody tr:nth-child(even) { background-color: #eee; }
tbody tr:hover { outline: 2px dotted orange; }
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Username</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr data-id='1'>
<td>1</td>
<td>Leanne Graham</td>
<td>Bret</td>
<td>Sincere#april.biz</td>
</tr>
<tr data-id='2'>
<td>2</td>
<td>Ervin Howell</td>
<td>Antonette</td>
<td>Shanna#melissa.tv</td>
</tr>
<tr data-id='3'>
<td>3</td>
<td>Clementine Bauch</td>
<td>Samantha</td>
<td>Nathan#yesenia.net</td>
</tr>
<tr data-id='4'>
<td>4</td>
<td>Patricia Lebsack</td>
<td>Karianne</td>
<td>Julianne.OConner#kory.org</td>
</tr>
<tr data-id='5'>
<td>5</td>
<td>Chelsey Dietrich</td>
<td>Kamren</td>
<td>Lucio_Hettinger#annie.ca</td>
</tr>
</tbody>
</table>
A vanilla based implementation of a component-like approach which is partially configurable via data-* attributes then possibly might look like the next provided example code ...
function emptyElementNode(node) {
[...node.childNodes].forEach(child => child.remove());
}
function clearTableContent(root) {
[
...root.querySelectorAll('thead'),
...root.querySelectorAll('tbody'),
].forEach(child => child.remove());
}
function createTableHead(headerContentList) {
const elmThead = document.createElement('thead');
const elmTr = headerContentList
.reduce((root, content) => {
const elmTh = document.createElement('th');
elmTh.textContent = content;
root.appendChild(elmTh);
return root;
}, document.createElement('tr'));
elmThead.appendChild(elmTr);
return elmThead;
}
function createTableBody(rowContentKeyList, userList) {
return userList
.reduce((elmTbody, userItem) => {
const elmTr = rowContentKeyList
.reduce((root, key) => {
const elmTd = document.createElement('td');
elmTd.textContent = userItem[key];
root.appendChild(elmTd);
return root;
}, document.createElement('tr'));
elmTr.dataset.id = userItem.id;
elmTbody.appendChild(elmTr);
return elmTbody;
}, document.createElement('tbody'));
}
function createAndRenderPostItem(root, { title, body }) {
const elmDt = document.createElement('dt');
const elmDd = document.createElement('dd');
elmDt.textContent = title;
elmDd.textContent = body;
root.appendChild(elmDt);
root.appendChild(elmDd);
return root;
}
function updateSelectedStates(selectedRow) {
[...selectedRow.parentNode.children]
.forEach(rowNode =>
rowNode.classList.remove('selected')
);
selectedRow.classList.add('selected');
}
function handleUserPostsRequestFromBoundData({ target }) {
const { postsRoot, requestUrl, placeholder } = this;
const currentRow = target.closest('tr');
const userId = currentRow?.dataset?.id;
if (userId) {
createListOfUserPosts({
postsRoot,
url: requestUrl.replace(placeholder, userId)
});
updateSelectedStates(currentRow);
}
}
async function createListOfUserPosts({ postsRoot, url }) {
emptyElementNode(postsRoot);
if (postsRoot && url) {
const response = await fetch(url);
const postList = await response.json();
postList.reduce(createAndRenderPostItem, postsRoot);
}
}
async function createListOfUsers({ usersRoot, postsRoot }) {
const usersRequestUrl = usersRoot.dataset.request;
const userPostsRequestUrl = postsRoot.dataset.request;
const userPostsPlaceholder = postsRoot.dataset.placeholder;
const response = await fetch(usersRequestUrl);
const userList = await response.json();
if (userList.length >= 1) {
const displayConfig = JSON.parse(
usersRoot.dataset.display ?? '{}'
);
const headerContentList = Object.values(displayConfig);
const rowContentKeyList = Object.keys(displayConfig);
emptyElementNode(postsRoot);
clearTableContent(usersRoot);
usersRoot.appendChild(
createTableHead(headerContentList)
);
usersRoot.appendChild(
createTableBody(rowContentKeyList, userList)
);
usersRoot.addEventListener(
'click',
handleUserPostsRequestFromBoundData
.bind({
postsRoot,
requestUrl: userPostsRequestUrl,
placeholder: userPostsPlaceholder,
})
);
}
}
function initializeUserPostsComponent(root) {
const usersRoot = root.querySelector('[data-users]');
const postsRoot = root.querySelector('[data-posts]');
createListOfUsers({ usersRoot, postsRoot });
}
document
.querySelectorAll('[data-user-posts]')
.forEach(initializeUserPostsComponent);
body { margin: 0 0 0 2px; font-size: .8em; }
table { border-collapse: collapse; }
table caption { text-align: left; padding: 3px; }
thead th { color: #fff; font-weight: bolder; background-color: #009577; }
th, td { padding: 3px 5px; color: #0a0a0a; }
tbody tr:nth-child(even) { background-color: #eee; }
tbody tr:hover { outline: 2px dotted orange; }
tbody tr.selected { background-color: rgb(255 204 0 / 18%); }
tbody tr { cursor: pointer; }
[data-user-posts]::after { clear: both; display: inline-block; content: ''; }
.user-overview { float: left; width: 63%; }
.user-posts { float: right; width: 36%; }
.user-posts h3 { margin: 0; padding: 4px 8px; font-size: inherit; font-weight: normal; }
<article data-user-posts>
<table
data-users
data-request="https://jsonplaceholder.typicode.com/users"
data-display='{"id":"Id","name":"Name","username":"Username","email":"Email"}'
class="user-overview"
>
<caption>Select a user to view posts</caption>
</table>
<div class="user-posts">
<h3>Posts:</h3>
<dl
data-posts
data-request="https://jsonplaceholder.typicode.com/users/:userId/posts"
data-placeholder=":userId"
>
</dl>
</div>
<article>
To add a click event handler to a table row with JavaScript, we can loop through each row and set the onclick property of each row to an event handler.
For instance, we add a table by writing:
<table>
<tbody>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>baz</td>
<td>qux</td>
</tr>
</tbody>
</table>
Then we write:
const createClickHandler = (row) => {
return () => {
const [cell] = row.getElementsByTagName("td");
const id = cell.innerHTML;
console.log(id);
};
};
const table = document.querySelector("table");
for (const currentRow of table.rows) {
currentRow.onclick = createClickHandler(currentRow);
}
to add event handlers to each row.
Reference : https://thewebdev.info/2021/09/12/how-to-add-an-click-event-handler-to-a-table-row-with-javascript/#:~:text=Row%20with%20JavaScript-,To%20add%20an%20click%20event%20handler%20to%20a%20table%20row,row%20to%20an%20event%20handler.&text=to%20add%20event%20handlers%20toe,table%20row%20as%20a%20parameter.
I have this fiddle:
https://jsfiddle.net/n9epsy5x/2/
I've got drag and drop working for the column headers, but I'd like a header's whole column to move when dragging and dropping the header. How can I pull this off in plain Javascript (VanillaJS)?
I tried adding classes to the table headers and accompanying column elements to be able to target the column elements to get them to move, but I couldn't get that to work.
Any help would be greatly appreciated. Thanks!
var source;
function isbefore(a, b) {
if (a.parentNode == b.parentNode) {
for (var cur = a; cur; cur = cur.previousSibling) {
if (cur === b) {
return true;
}
}
}
return false;
}
function dragenter(e) {
var targetelem = e.target;
if (targetelem.nodeName == "TD") {
targetelem = targetelem.parentNode;
}
if (isbefore(source, targetelem)) {
targetelem.parentNode.insertBefore(source, targetelem);
} else {
targetelem.parentNode.insertBefore(source, targetelem.nextSibling);
}
}
function dragstart(e) {
source = e.target;
e.dataTransfer.effectAllowed = 'move';
}
[draggable] {
user-select: none;
}
body {
background-color: #fff;
color: #303;
font-family: sans-serif;
text-align: center;
}
li {
border: 2px solid #000;
list-style-type: none;
margin: 2px;
padding: 5px;
}
ul {
margin: auto;
text-align: center;
width: 25%;
}
<table>
<thead>
<tr>
<th ondragstart="dragstart(event)" ondragenter="dragenter(event)" draggable="true">
Column 1
</th>
<th ondragstart="dragstart(event)" ondragenter="dragenter(event)" draggable="true">
Column 2
</th>
<th ondragstart="dragstart(event)" ondragenter="dragenter(event)" draggable="true">
Column 3
</th>
</tr>
</thead>
<tbody>
<tr>
<td>hhgr</td>
<td>ffrr</td>
<td>qedf</td>
</tr>
<tr>
<td>wdfe</td>
<td>cjnb</td>
<td>cdke</td>
</tr>
<tr>
<td>awjb</td>
<td>cdjk</td>
<td>ijfe</td>
</tr>
</tbody>
</table>
$(function () {
var people = [];
var ctCells = [], questionCells = [], userCells = [];
var $tBody = $("#userdata tbody");
$.getJSON('https://api.myjson.com/bins/18g7fm', function (data) {
$.each(data.ct_info, function (i, f) {
ctCells.push(`<td id=${f.id}>${f.id}</td><td>${f.name}</td>`);
var users = []
var question = []
f.Qid_info.forEach((x) => {
x.user_info.forEach((y) => {
//avoid duplicates
var foundUser = users.find((user) => {
return user.id === y.id
})
if (!foundUser) {
users.push(y)
}
})
})
f.Qid_info.forEach((x) => {
var foundQuestion = question.find((questions) => {
return questions.id === x.id
})
if (!foundQuestion) {
question.push(x)
}
})
$.each(question, function (i, question) {
ctCells.push(`<td colspan="2"> </td>`)
questionCells.push(`<td id=${question.id}>${question.id}</td><td>${question.isActive}</td><td>${question["is complex"]}</td><td>${question["is breakdown"]}</td>`);
})
$.each(users, function (i, user) {
var a = user.data.map(function (key) {
return key
})
// ctCells.push(`<td colspan="2"> </td>`)
// questionCells.push(`<td colspan="${lent+1}"> </td>`)
userCells.push(`<td><div style="display:flex; flex-direction:row">
${
users.forEach(val => {
`<div style="display:flex; flex-direction:column">
<div>${val.id}${val.name}</div>
<div>${val.updatedAt}</div>
<div style="display:flex; flex-direction:column">
${user.data.forEach(IN => {
`
<div style="display:flex; flex-direction:row">
<div><p>${console.log(IN.git_ids)}</p></div>
</div>
`
})}
</div>
</div>`
})
}
</div></td>`)
// userCells.push(`<td id=${user.id}>UserId--- ${user.id} UserName---- ${user.name}${a.map(value => {
// return `
// <div id="${user.id}" >
// <td><input type="checkbox" style="display: inline;"> </td>
// <td> <span id="text">${Object.keys(value)[0]}</span></td>
// <td> <textarea type="text" class="gitplc" placeholder="GitId">${ value.git_ids}</textarea> </td> j
// </div>
// `
// })
// }</td><td>${user.updatedAt}</td>`);
})
});
console.log(userCells)
$.each(ctCells, function (i) {
console.log(userCells)
$tBody.append(`<tr>${ctCells[i]}${questionCells[i]}${userCells[i]}</tr>`)
})
});
});
#scrlSec {
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
/* .checkSec { width: 60%; } */
.checkSec .tbl {
padding-top: 20px;
}
.checkSec td {
padding-left: 10px;
}
.checkSec .btnGreen {
color: white;
background-color: #4CAF50;
border: none;
padding: 15px 32px;
width: 100%;
text-decoration: none;
}
.checkSec .gitplc {
width: 80%;
}
.checkSec #text {
font-size: 14px;
}
.checkSec .tbl .colOne {
width: 50%;
float: left;
}
.checkSec .tbl .colTwo {
width: 50%;
float: right;
}
#user {
overflow: auto;
}
.flex-container {
display: flex;
}
th,
td {
font-weight: normal;
padding: 5px;
text-align: center;
width: 120px;
vertical-align: top;
}
th {
background: #00B0F0;
}
tr+tr th,
tbody th {
background: #DAEEF3;
}
tr+tr,
tbody {
text-align: left
}
table,
th,
td {
border: solid 1px;
border-collapse: collapse;
table-layout: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='userdata'>
<thead>
<tr>
<th colspan="2" id="ct">CT INFO</th>
<th colspan="4" id="que">Question</th>
<th id="user">User Info</th>
</tr>
<tr>
<th>CT ID</th>
<th>CT</th>
<th>Id</th>
<th>isActive</th>
<th>is Complex</th>
<th>is Breakdown</th>
<th>USER</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I am printing json data in table format in html. But in users column i am getting undefined but when i print those variable in console that is printing correct value.
This is my json api . When i print value in foreach loop of user i am getting undefined but on console.log i have proper value printing in console.
https://api.myjson.com/bins/18g7fm
This is happening because you are using forEach() inside a template literal. forEach() returns undefined by default. Use map() function instead.
userCells.push(`<td><div style="display:flex; flex-direction:row">
${
users.map(val => {
return `<div style="display:flex; flex-direction:column">
<div>${val.id}${val.name}</div>
<div>${val.updatedAt}</div>
<div style="display:flex; flex-direction:column">
${user.data.map(IN => {
return `
<div style="display:flex; flex-direction:row">
<div><p>${console.log(IN.git_ids)}</p></div>
</div>
`
})}
</div>
</div>`
})
}
</div></td>`)
I'm learning Javascript and i'm stuck at the moment. When the user input their first name, last name, age and clicks on the button "add", 1 new row and 4 new cells are being added to the table with the value of the users input.
My question is: how do I get the first cell to be a number? Which in this case should be number 4. If the user adds another row with value it should become number 5. etc.
If somebody could point me in a direction or show me another way to do it, that would help. Thanks! (css added just for visuals)
function allID(id) {
return document.getElementById(id);
}
function allEvents() {
allID("voegdatatoe").onclick = function () {
voegToeGegevens();
};
}
allEvents();
function voegToeGegevens() {
var formulier = allID("invoerformulier");
var nieuweGegevens = [];
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i] = formulier.elements[i].value;
}
var uitvoertabel = allID("uitvoertabel");
var nieuweRij = uitvoertabel.insertRow(-1);
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i);
NieuweCell.innerHTML = nieuweGegevens[i];
}
}
var row = document.getElementsByClassName("rownmr");
var i = 0;
for (i = 0; i < row.length; i++) {
row[i].innerHTML = i + 1;
}
table,
th,
td {
border-collapse: collapse;
border: 1px solid black;
}
th,
td {
padding: 5px;
}
th {
text-align: left;
background-color: #c95050;
color: white;
}
.uitvoertabel {
width: 60%;
}
.uitvoertabel tr:nth-child(even) {
background-color: #eee;
}
.uitvoertabel tbody tr td:first-child {
width: 30px;
}
.invoerform {
margin-top: 50px;
width: 30%;
}
.invoerform input,
label {
display: block;
}
.invoerform label {
margin-bottom: 5px;
margin-top: 10px;
}
#voegdatatoe {
margin-top: 30px;
}
input:focus {
border: 1px solid #d45757;
outline: none;
}
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th>
<th>Voornaam</th>
<th>Achternaam</th>
<th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td class="rownmr"></td>
<td>Johan</td>
<td>cruijff</td>
<td>54</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Frans</td>
<td>Bauer</td>
<td>47</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Willem</td>
<td>van Oranje</td>
<td>80</td>
</tr>
</tbody>
</table>
<form action="" id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
</form>
<button id="voegdatatoe">Voeg toe</button>
There are a number of ways you could store this information, from a global variable (not recommended) to some local closure, or even localStorage. But you have the information in the DOM, so it might be simplest to use it.
One way to do this would be to scan the ids, find their maximum, and add one to it. This involves a few changes to your code. First, we would add some code to scan your id cells for the largest value:
var rows = document.getElementsByClassName("rownmr");
var highestId = Math.max(...([...rows].map(row => Number(row.textContent))))
Then we would start your content array with a new value one higher than that maximum:
var nieuweGegevens = [highestId + 1];
And your loop needs to take this into account by adding one to the index
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i + 1] = formulier.elements[i].value;
}
Finally, we need to add the right class to that new cell so that on the next call, it will continue to work:
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i);
NieuweCell.innerHTML = nieuweGegevens[i];
if (i === 0) { /**** new ****/
NieuweCell.classList.add("rownmr") /**** new ****/
} /**** new ****/
}
You can see these changes inline in this snippet:
function allID(id) {
return document.getElementById(id);
}
function allEvents() {
allID("voegdatatoe").onclick = function () {
voegToeGegevens();
};
}
allEvents();
function voegToeGegevens() {
var formulier = allID("invoerformulier");
var rows = document.getElementsByClassName("rownmr");
var highestId = Math.max(...([...rows].map(row => Number(row.textContent))))
var nieuweGegevens = [highestId + 1];
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i + 1] = formulier.elements[i].value;
}
var uitvoertabel = allID("uitvoertabel");
var nieuweRij = uitvoertabel.insertRow(-1);
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i);
NieuweCell.innerHTML = nieuweGegevens[i];
if (i === 0) {
NieuweCell.classList.add("rownmr")
}
}
}
var row = document.getElementsByClassName("rownmr");
var i = 0;
for (i = 0; i < row.length; i++) {
row[i].innerHTML = i + 1;
}
table,
th,
td {
border-collapse: collapse;
border: 1px solid black;
}
th,
td {
padding: 5px;
}
th {
text-align: left;
background-color: #c95050;
color: white;
}
.uitvoertabel {
width: 60%;
}
.uitvoertabel tr:nth-child(even) {
background-color: #eee;
}
.uitvoertabel tbody tr td:first-child {
width: 30px;
}
.invoerform {
margin-top: 50px;
width: 30%;
}
.invoerform input,
label {
display: block;
}
.invoerform label {
margin-bottom: 5px;
margin-top: 10px;
}
#voegdatatoe {
margin-top: 30px;
}
input:focus {
border: 1px solid #d45757;
outline: none;
}
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th>
<th>Voornaam</th>
<th>Achternaam</th>
<th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td class="rownmr"></td>
<td>Johan</td>
<td>cruijff</td>
<td>54</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Frans</td>
<td>Bauer</td>
<td>47</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Willem</td>
<td>van Oranje</td>
<td>80</td>
</tr>
</tbody>
</table>
<form action="" id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
</form>
<button id="voegdatatoe">Voeg toe</button>
Note that this will continue to work on subsequent adds.
Add additional the length+1 param in the arrays of data
function allID(id) {
return document.getElementById(id);
}
function allEvents() {
allID("voegdatatoe").onclick = function () {
voegToeGegevens();
};
}
allEvents();
function voegToeGegevens() {
var row = document.getElementsByTagName("tr");
var formulier = allID("invoerformulier");
var nieuweGegevens = [];
nieuweGegevens.push(row.length) //length param for first column
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i+1] = formulier.elements[i].value; //saving values from i=1
}
var uitvoertabel = allID("uitvoertabel");
var nieuweRij = uitvoertabel.insertRow(-1);
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i);
NieuweCell.innerHTML = nieuweGegevens[i];
}
}
var row = document.getElementsByClassName("rownmr");
var i = 0;
for (i = 0; i < row.length; i++) {
row[i].innerHTML = i + 1;
}
table,
th,
td {
border-collapse: collapse;
border: 1px solid black;
}
th,
td {
padding: 5px;
}
th {
text-align: left;
background-color: #c95050;
color: white;
}
.uitvoertabel {
width: 60%;
}
.uitvoertabel tr:nth-child(even) {
background-color: #eee;
}
.uitvoertabel tbody tr td:first-child {
width: 30px;
}
.invoerform {
margin-top: 50px;
width: 30%;
}
.invoerform input,
label {
display: block;
}
.invoerform label {
margin-bottom: 5px;
margin-top: 10px;
}
#voegdatatoe {
margin-top: 30px;
}
input:focus {
border: 1px solid #d45757;
outline: none;
}
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th>
<th>Voornaam</th>
<th>Achternaam</th>
<th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td class="rownmr"></td>
<td>Johan</td>
<td>cruijff</td>
<td>54</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Frans</td>
<td>Bauer</td>
<td>47</td>
</tr>
<tr>
<td class="rownmr"></td>
<td>Willem</td>
<td>van Oranje</td>
<td>80</td>
</tr>
</tbody>
</table>
<form action="" id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
</form>
<button id="voegdatatoe">Voeg toe</button>
As I note that none of the answers made, does not seem to have the approval of Niekket (no validation for anybody),
and that the question asked is accompanied by a very rough example (the author admits to being bloked in his apprenticeship), using a lot of useless code...
So I propose this complete solution, which I hope is enlightening enough on the proper way of coding its problem ( imho ).
const
TableBody_uitvoertabel = document.querySelector('#uitvoertabel > tbody'),
form_invoerformulier = document.querySelector('#invoerformulier'),
in_voornaam = document.querySelector('#voornaam'),
in_achternaam = document.querySelector('#achternaam'),
in_leeftijd = document.querySelector('#leeftijd')
;
var
RowCount = 0; // global..
// place numbers in the first column
document.querySelectorAll('#uitvoertabel > tbody > tr td:first-child').forEach(
elmTR=>{ elmTR.textContent = ++RowCount }
);
form_invoerformulier.onsubmit = function(e) {
e.preventDefault();
let
column = 0,
row = TableBody_uitvoertabel.insertRow(-1)
;
row.insertCell(column++).textContent = ++RowCount;
row.insertCell(column++).textContent = in_voornaam.value;
row.insertCell(column++).textContent = in_achternaam.value;
row.insertCell(column++).textContent = in_leeftijd.value;
this.reset();
}
table, th, td {
border-collapse: collapse;
border: 1px solid black;
}
th, td { padding: 5px; }
th {
text-align: left;
background-color: #c95050;
color: white;
}
table.uitvoertabel { width: 60%; }
table.uitvoertabel tr:nth-child(even) {
background-color: #eee;
}
table.uitvoertabel tbody tr td:first-child {
width: 30px;
}
form.invoerform {
margin-top: 50px;
width: 30%;
}
form.invoerform input,
form.invoerform label {
display: block;
}
form.invoerform label {
margin-bottom: 5px;
margin-top: 10px;
}
form.invoerform button {
margin-top: 30px;
}
form.invoerform input:focus {
border-color: #d45757;
outline: none;
}
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th><th>Voornaam</th><th>Achternaam</th><th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td></td><td>Johan</td><td>cruijff</td><td>54</td>
</tr>
<tr>
<td></td><td>Frans</td><td>Bauer</td><td>47</td>
</tr>
<tr>
<td></td><td>Willem</td><td>van Oranje</td><td>80</td>
</tr>
</tbody>
</table>
<form id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
<button type="submit">Voeg toe</button>
<button type="reset">Reset</button>
</form>
I think that the main issue is that you only manually set the rownmrs for the first time from line var row = document.getElementsByClassName("rownmr");
rather than every time you click on the "Voeg toe" button.
Ideally, for your hard coded numbers, they would be in the markup and the logic to grab the next rownmr to display and the adding of that cell happens on click.
html
<table class="uitvoertabel" id="uitvoertabel">
<thead>
<tr>
<th></th>
<th>Voornaam</th>
<th>Achternaam</th>
<th>Leeftijd</th>
</tr>
</thead>
<tbody>
<tr>
<td class="rownmr">1</td>
<td>Johan</td>
<td>cruijff</td>
<td>54</td>
</tr>
<tr>
<td class="rownmr">2</td>
<td>Frans</td>
<td>Bauer</td>
<td>47</td>
</tr>
<tr>
<td class="rownmr">3</td>
<td>Willem</td>
<td>van Oranje</td>
<td>80</td>
</tr>
</tbody>
</table>
<form action="" id="invoerformulier" class="invoerform">
<label>Voornaam:</label>
<input type="text" name="vnaam" id="voornaam">
<label>Achternaam:</label>
<input type="text" name="anaam" id="achternaam">
<label>Leeftijd:</label>
<input type="text" name="points" id="leeftijd">
</form>
<button id="voegdatatoe">Voeg toe</button>
js
function allID(id) {
return document.getElementById(id);
}
function allEvents() {
allID("voegdatatoe").onclick = function () {
voegToeGegevens();
};
}
allEvents();
function voegToeGegevens() {
var formulier = allID("invoerformulier");
var nieuweGegevens = [];
for (var i = 0; i < formulier.length; i++) {
nieuweGegevens[i] = formulier.elements[i].value;
}
var allRownmrs = document.getElementsByClassName('rownmr');
var lastRownmr = allRownmrs[allRownmrs.length - 1].innerHTML;
var nextRownmr = parseInt(lastRownmr) + 1;
var uitvoertabel = allID("uitvoertabel");
var nieuweRij = uitvoertabel.insertRow(-1);
for (i = 0; i < 4; i++) {
var NieuweCell = nieuweRij.insertCell(i)
// you probably can refactor here
if (i === 0) {
NieuweCell.innerHTML = nextRownmr
} else {
NieuweCell.innerHTML = nieuweGegevens[i - 1];
}
}
}
I'want to add an eventListener to the table cells so each time a table cell is clicked to execute a function .
var getDaysInMonth = function (year, month) {
return new Date(year, month, 0).getDate();
}
var calendar = {
month: function () {
var d = new Date();
return d.getMonth() + this.nextMonth;
},
year: function () {
var y = new Date();
return y.getFullYear();
},
nextMonth: 1,
cellColor: 'white',
}
var loopTable = function () {
var daysInMonth = getDaysInMonth(calendar.year(), calendar.month());
var table = document.getElementById('myTable');
var rows = table.rows;
var l = 1;
var month = calendar.month();
var year = calendar.year();
var firstDay = new Date(year + "-" + month).getDay();
var currentDay = new Date().getDay();
var dayOfMonth = new Date().getDate();
for (let i = 1; i < rows.length; i++) {
if (rows[i] == rows[1]) {
var k = 1;
for (let j = firstDay; j < rows[i].cells.length; j++) {
if (k === dayOfMonth && calendar.nextMonth === 1) {
rows[i].cells[j].style.backgroundColor = calendar.cellColor;
}
if (k <= daysInMonth) {
rows[i].cells[j].innerHTML = k;
k++
}
}
} else {
for (let j = 0; j < rows[i].cells.length; j++) {
if (k === dayOfMonth && calendar.nextMonth === 1) {
rows[i].cells[j].style.backgroundColor = calendar.cellColor;
}
if (k <= daysInMonth) {
rows[i].cells[j].innerHTML = k;
k++
}
}
}
}
}
loopTable();
clickCell();
function monthTitle() {
var monthsArray = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sept.', 'Oct.', 'Nov.', 'Dec.'];
monthNum = calendar.month();
var monthName = monthsArray[calendar.month() - 1] + '' + calendar.year();
var title = document.getElementById('calendarTitle');
var nextArrow = document.getElementById('nxt');
var leftArrow = document.getElementById('prev');
if (monthName === ('Dec.' + '' + calendar.year())){
xmas();
}
if (monthNum >= 12) {
nextArrow.className += ' inactiveLink';
} else if (monthNum <= 1) {
leftArrow.className += ' inactiveLink';
} else {
nextArrow.classList.remove('inactiveLink');
leftArrow.classList.remove('inactiveLink');
}
title.innerHTML = '';
var titleNode = document.createTextNode(monthName);
title.appendChild(titleNode);
}
monthTitle();
function nextMonth() {
clearTable();
calendar.nextMonth += 1;
monthTitle();
loopTable();
}
function previousMonth() {
clearTable();
calendar.nextMonth -= 1;
monthTitle();
loopTable();
}
function clearTable() {
var table = document.getElementById('myTable');
var rows = table.rows;
for (var i = 1; i < rows.length; i++) {
cells = rows[i].cells;
for (var j = 0; j < cells.length; j++) {
if (cells[j].innerHTML = '') {
cells[j].style.display = 'none';
}
cells[j].innerHTML = '';
cells[j].style.backgroundColor = '#D9534F';
cells[j].style.emptyCells = 'hide';
}
}
}
var next = document.getElementById('nxt');
var previous = document.getElementById('prev');
var table = document.getElementById('myTable');
var cell = table.rows;
next.addEventListener('click', nextMonth);
previous.addEventListener('click', previousMonth);
function clickCell() {
var row = document.getElementById('myTable').rows;
for (var i = 0; i < row.length; i++) {
for (var j = 0; j < row[i].cells.length; j++ ) {
row[i].cells[j].addEventListener('click', function(){
console.log('click');
})
}
}
}
clickCell();
body {
background-color: rgb(0, 121, 191);
}
table {
width: 50%;
background-color: #D9534F;
border: 1px solid white;
padding: 10px;
padding-bottom: 20px;
font-size: 25px;
border-radius: 25px;
position: relative;
margin: auto;
}
td {
border: 1px solid white;
text-align: center;
font-weight: 600;
font-size: 20px;
padding: 20px;
}
th {
height: 50px;
}
.calArrows {
text-decoration: none;
color: white;
font-size: 35px;
}
#nxt {
font-size: 30px;
position: absolute;
top: 0;
right: 25%
}
#prev {
font-size: 30px;
position: absolute;
top: 0;
left: 25%;
}
#calendarTitle {
font-family: 'Indie Flower', cursive;
font-weight: 600;
font-size: 25px;
color: white;
}
.inactiveLink {
cursor: not-allowed;
pointer-events: none;
}
#myTable {
empty-cells: hide;
}
.xmasDec {
width: 90%;
height: 70%;
position: absolute;
top: -10%;
left: 5%;
}
#calWraper {
position: relative;
}
#myCan {
position: absolute;
top: 0;
left: 10%;
width: 90%;
height: 70%;
opacity: 0, 5;
}
<body>
<canvas class="myCan" width="100" height="100"></canvas>
<div id="calWraper">
<table id="myTable">
<caption id="calendarTitle">Test</caption>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thur</th>
<th>Fri</th>
<th>Sat</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
<canvas id="myCan" width="200" height="200" style="background-color: transparent"></canvas>
<i class="fa fa-arrow-left" ></i>
<i class="fa fa-arrow-right" ></i>
</div>
</html>
I tried by creating a function that it will loop through rows and cells and add the eventListener to each . But it seems that its not working , its working on random instances which is really strange behavior . Here is the function i create:
function clickCell() {
var row = document.getElementById('myTable').rows;
for (var i = 0; i < row.length; i++) {
for (var j = 0; j < row[i].cells.length; j++ ) {
console.log(row[i].cells[j].innerHTML);
row[i].cells[j].addEventListener('click', function(){
console.log('click');
})
}
}
}
It seems your canvas is overlapping your table. Because of that td elements in your table are never clicked.
You will need to add CSS property pointer-events:none to your canvas.
#myCan {
...
pointer-events: none;
}
This way it won't block table from being clicked anymore.
You can also add event listeners to your cells way simpler:
document.querySelectorAll('#myTable td')
.forEach(e => e.addEventListener("click", function() {
// Here, `this` refers to the element the event was hooked on
console.log("clicked")
}));
That creates a separate function for each cell; instead, you could share one function without losing any functionality:
function clickHandler() {
// Here, `this` refers to the element the event was hooked on
console.log("clicked")
}
document.querySelectorAll('#myTable td')
.forEach(e => e.addEventListener("click", clickHandler));
Some browsers still don't have forEach on the HTMLCollection returned by querySelectorAll, but it's easily polyfilled:
if (!HTMLCollection.prototype.forEach) {
Object.defineProperty(HTMLCollection.prototype, "forEach", {
value: Array.prototype.forEach
});
}
If you have to support truly obsolete browsers that don't have Array.prototype.forEach, see the polyfill on MDN.
This is a case for event delegation: Hook the click event on the table (or table body), not individual cells, and then determine which cell was clicked by looking at event.target and its ancestors.
Simplified example:
document.querySelector("#my-table tbody").addEventListener("click", function(event) {
var td = event.target;
while (td !== this && !td.matches("td")) {
td = td.parentNode;
}
if (td === this) {
console.log("No table cell found");
} else {
console.log(td.innerHTML);
}
});
Live Copy:
document.querySelector("#my-table tbody").addEventListener("click", function(event) {
var td = event.target;
while (td !== this && !td.matches("td")) {
td = td.parentNode;
}
if (td === this) {
console.log("No table cell found");
} else {
console.log(td.innerHTML);
}
});
table, td, th {
border: 1px solid #ddd;
}
table {
border-collapse: collapse;
}
td, th {
padding: 4px;
}
<table id="my-table">
<thead>
<tr>
<th>First</th>
<th>Last</th>
</tr>
</thead>
<tbody>
<tr>
<td>Joe</td>
<td>Bloggs</td>
</tr>
<tr>
<td>Muhammad</td>
<td>Abdul</td>
</tr>
<tr>
<td>Maria</td>
<td>Gonzales</td>
</tr>
</tbody>
</table>
Note that instead of the loop you could use the new (experimental) closest method on elements:
var td = event.target.closest("td");
...but A) It's still experimental, and B) It won't stop when it reaches the tbody, so in theory if you had nested tables, would find the wrong cell.
If you need to support browsers that don't have Element.prototype.matches, in this specific case you could use td.tagName !== "TD" instead of !td.matches("td") (note the capitalization).
Using only the DOM objects
Here's an example cell wise event listener added on an HTML table (TicTacToe). It can be achieved easily using 'this' keyword and 'querySelectorAll'
The logic is in the JavaScript file:
First, get all the cells by their 'tag' ("td") using 'querySelectorAll' and save it as a list
Add an event listener to each of the cells, and give a function name to do whatever you want
Inside the event listener function, using this keyword update the cell content, or call other functions or do whatever task you have to complete.
var cells = document.querySelectorAll("td");
for (var cell of cells) {
cell.addEventListener('click', marker)
}
function marker() {
if (this.textContent === 'X') {
this.innerHTML = "O";
} else if (this.textContent === 'O') {
this.innerHTML = " ";
} else {
this.innerHTML = "X";
}
}
td {
text-align: center;
font-size: 50px
}
table,
th,
td {
border: 2px solid black;
width: 300px;
height: 100px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Tic Tac Toe</title>
</head>
<body>
<table id="ticTac">
<tbody>
<tr>
<td>. </td>
<td>. </td>
<td>. </td>
</tr>
<tr>
<td>. </td>
<td>. </td>
<td>. </td>
</tr>
<tr>
<td>. </td>
<td>. </td>
<td>. </td>
</tr>
</tbody>
</table>
</body>
</html>