To update LocalStorage values from a dynamically created HTML table - javascript

The HTML table is dynamically created with the function createTableRow(empDetail), which is working but when the rows/cells values are updated/changed it reflects in the HTML table but I want the same respective changed values to get changed in LocalStorage against the respective id. Help is needed for function tableUpdate()
Note: There is only one key i.e. empDetails and the same key has multiple id's of respective rows (Employee) created
"use strict";
let addNewEmployee = document.getElementById("addNewEmployee");
let modal = document.getElementById("favDialog");
let closeModal = document.getElementById("cancelModal");
let modalForm = document.getElementById("modal-form");
let submitModal = document.getElementById("submitModal");
let tableContainerHeader = document.querySelector(".table-container-header");
let tableContainerContent = document.querySelector(".table-container-content");
let empTable = document.getElementById("employeeTable");
const showModal = addNewEmployee.addEventListener("click", function() {
modal.showModal();
});
closeModal.addEventListener("click", function() {
modal.close();
});
let employeeId = document.getElementById("employeeId");
let employeeName = document.getElementById("employeeName");
let designation = document.getElementById("designation");
let salary = document.getElementById("salary");
let uniqueEmpId = document.getElementById("empDetailId");
let tr = null;
let empDetails = [];
if (localStorage.getItem("empDetails")) {
empDetails.map((empDetail) => {
createTableRow(empDetail);
});
}
let onModalSubmit = modal.addEventListener("submit", function(e) {
e.preventDefault();
if (tr == null) {
if (employeeId && employeeName && designation && salary != "") {
let empDetail = {
id: new Date().getTime(),
name: {
employeeIdLocal: employeeId.value,
employeeNameLocal: employeeName.value,
designationLocal: designation.value,
salaryLocal: salary.value,
uniqueEmpId: new Date().getTime(),
},
};
modal.close();
empDetails.push(empDetail);
localStorage.setItem("empDetails", JSON.stringify(empDetails));
modalForm.reset();
createTableRow(empDetail);
}
} else {
tableUpdate(e);
}
});
/////// Create Table Row
function createTableRow(empDetail) {
const tEmployeeMarkup = `
<tr class="fullEmpDetail">
<td id="teId">${empDetail.name.employeeIdLocal}</td>
<td id="teName">${empDetail.name.employeeNameLocal}</td>
<td id="teDesignation">${empDetail.name.designationLocal}</td>
<td id="teSalary">$${empDetail.name.salaryLocal}</td>
<td>
<i class="fas fa-eye"></i>
<i value="Edit" type="button" id="update-row" class="edit-row fas fa-pencil-alt"></i>
<i value="Delete" type="button" class="remove-row fas fa-trash-alt"></i>
</td>
<td id="empDetailId" class="empDetailId">${empDetail.id}</td>
</tr>
`;
empTable.innerHTML += tEmployeeMarkup;
document.getElementById("modal-form").reset();
}
/////// Remove Row
function onDeleteRow(e) {
if (!e.target.classList.contains("remove-row")) {
return;
}
const btn = e.target;
btn.closest("tr").remove();
}
tableContainerContent.addEventListener("click", onDeleteRow);
//////////// Edit Row
tableContainerContent.addEventListener("click", onEditRow);
function onEditRow(e) {
if (e.target.classList.contains("edit-row")) {
modal.showModal();
tr = e.target.parentNode.parentNode;
// console.log(tr);
let tableEmpId = tr.cells[0].textContent;
let tableEmpName = tr.cells[1].textContent;
let tableEmpDesignation = tr.cells[2].textContent;
let tableEmpSalary = tr.cells[3].textContent;
employeeId.value = tableEmpId;
employeeName.value = tableEmpName;
designation.value = tableEmpDesignation;
salary.value = tableEmpSalary;
}
}
///////////////// Update Row
function tableUpdate(e) {
let tableEmpId = document.getElementById("teId");
let tableEmpName = document.getElementById("teName");
let tableEmpDesignation = document.getElementById("teDesignation");
let tableEmpSalary = document.getElementById("teSalary");
tr.cells[0].textContent = employeeId.value;
tr.cells[1].textContent = employeeName.value;
tr.cells[2].textContent = designation.value;
tr.cells[3].textContent = salary.value;
modalForm.reset();
modal.close();
let tableEmpIDs = document.querySelectorAll(".empDetailId");
let empDetails = JSON.parse(localStorage.getItem("empDetails"));
for (let row = 0; row < tableEmpIDs.length; row++) {
for (let i = 0; i < empDetails.length; i++) {
empDetails[i].name.employeeIdLocal = tableEmpId.textContent;
empDetails[i].name.employeeNameLocal = tableEmpName.textContent;
empDetails[i].name.designationLocal = tableEmpDesignation.textContent;
empDetails[i].name.salaryLocal = tableEmpSalary.textContent;
break;
}
}
localStorage.setItem("empDetails", JSON.stringify(empDetails));
}
table
/* th,
td,
tr */
{
border: black solid 1px;
width: 1000px;
text-align: center;
}
table td,
table th {
border: solid 1px black;
width: 200px;
}
table {
border-collapse: collapse;
}
.fas {
margin: 0 10px;
}
.empDetailIdHeader,
.empDetailId {
display: none;
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<div class="main-container">
<h2>Employee Details</h2>
<button id="addNewEmployee">+ Add New Employee</button>
<div class="table-container-header">
<table>
<tr>
<th>Employee ID</th>
<th>Name</th>
<th>Designation</th>
<th>Salary</th>
<th>Action</th>
<th class="empDetailIdHeader">Local Storage ID</th>
</tr>
</table>
</div>
<div class="table-container-content">
<table id="employeeTable">
</table>
</div>
</div>
<!-- Model Code -->
<div id="#modal-container">
<dialog id="favDialog">
<h2>Enter Employee Details</h2>
<form id="modal-form" method="dialog">
<section>
<p>
<label for="employeeId">Employee ID: </label
><input type="text" id="employeeId" />
</p>
<p>
<label for="employeeName">Name: </label
><input type="text" id="employeeName" />
</p>
<p>
<label for="designation">Designation: </label
><input type="text" id="designation" />
</p>
<p>
<label for="salary">Salary: </label
><input type="text" id="salary" />
</p>
</section>
<menu>
<button id="cancelModal" type="reset">Cancel</button>
<button type="submit" id="submitModal">SUBMIT</button>
</menu>
</form>
</dialog>
</div>
<script src="./script.js"></script>
</body>
</html>

I think you'd be better off just writing the JSON from scratch each time, rather than trying to update it. Something like...
let entries = document.querySelectorAll("table.empDetailsTable tr");
let json = [], props = ['employeeIdLocal', 'employeeNameLocal', 'designationLocal', 'salaryLocal'] // in order that they appear in the table
entries.forEach(row => {
let data = {}
row.querySelectorAll('td').forEach((el, i) => {
data[props[i]] = el.innerText;
})
json.push(data);
})
localStorage.setItem("empDetails", JSON.stringify(data));
I didn't understand your data structure, but hopefully this will suffice or point you in the right direction.

To update LocalStorage values from a dynamically created HTML table
let addNewEmployee = document.getElementById("addNewEmployee");
let modal = document.getElementById("favDialog");
let closeModal = document.getElementById("cancelModal");
let modalForm = document.getElementById("modal-form");
let submitModal = document.getElementById("submitModal");
let tableContainerHeader = document.querySelector(".table-container-header");
let tableContainerContent = document.querySelector(".table-container-content");
let empTable = document.getElementById("employeeTable");
const showModal = addNewEmployee.addEventListener("click", function () {
modal.showModal();
});
closeModal.addEventListener("click", function () {
modal.close();
});
let employeeId = document.getElementById("employeeId");
let employeeName = document.getElementById("employeeName");
let designation = document.getElementById("designation");
let salary = document.getElementById("salary");
let uniqueEmpId = document.getElementById("empDetailId");
let tr = null;
let empDetails = [];
//edit
let editID = "";
let onModalSubmit = modal.addEventListener("submit", function (e) {
e.preventDefault();
if (tr == null && addNewEmployee) {
if (employeeId && employeeName && designation && salary != "") {
let empDetail = {
id: new Date().getTime(),
name: {
employeeIdLocal: employeeId.value,
employeeNameLocal: employeeName.value,
designationLocal: designation.value,
salaryLocal: salary.value,
uniqueEmpId: new Date().getTime(),
},
};
modal.close();
empDetails.push(empDetail);
localStorage.setItem("empDetails", JSON.stringify(empDetails));
modalForm.reset();
createTableRow(empDetail);
}
} else {
tableUpdate(tr);
tr = null;
}
});
/////// Create Table Row
function createTableRow(empDetail) {
const element = document.createElement("tr");
let attr = document.createAttribute("data-id");
attr.value = empDetail.id;
element.setAttributeNode(attr);
element.classList.add("fullEmpDetail");
element.innerHTML = `
<td id="teId">${empDetail.name.employeeIdLocal}</td>
<td id="teName">${empDetail.name.employeeNameLocal}</td>
<td id="teDesignation">${empDetail.name.designationLocal}</td>
<td id="teSalary">$${empDetail.name.salaryLocal}</td>
<td>
<i class="fas fa-eye"></i>
<i value="Edit" type="button" id="update-row" class="edit-row fas fa-pencil-alt"></i>
<i value="Delete" type="button" class="remove-row fas fa-trash-alt"></i>
</td>
`;
empTable.appendChild(element);
document.getElementById("modal-form").reset();
}
/////// Remove Row
function onDeleteRow(e) {
if (!e.target.classList.contains("remove-row")) {
return;
}
const btn = e.target;
btn.closest("tr").remove();
}
tableContainerContent.addEventListener("click", onDeleteRow);
//////////// Edit Row
tableContainerContent.addEventListener("click", onEditRow);
function onEditRow(e) {
if (e.target.classList.contains("edit-row")) {
modal.showModal();
tr = e.target.parentNode.parentNode;
// console.log(tr);
let tableEmpId = tr.cells[0].textContent;
let tableEmpName = tr.cells[1].textContent;
let tableEmpDesignation = tr.cells[2].textContent;
let tableEmpSalary = tr.cells[3].textContent;
employeeId.value = tableEmpId;
employeeName.value = tableEmpName;
designation.value = tableEmpDesignation;
salary.value = tableEmpSalary;
}
}
///////////////// Update Row
function tableUpdate(tr) {
let tableEmpId = document.getElementById("teId");
let tableEmpName = document.getElementById("teName");
let tableEmpDesignation = document.getElementById("teDesignation");
let tableEmpSalary = document.getElementById("teSalary");
console.log(tr);
tr.cells[0].textContent = employeeId.value;
tr.cells[1].textContent = employeeName.value;
tr.cells[2].textContent = designation.value;
tr.cells[3].textContent = salary.value;
editID = tr.dataset.id;
modalForm.reset();
modal.close();
editLocalStorage(editID, tr);
}
///////// Edit Local Storage
function editLocalStorage(editID, tr) {
let empDetails = JSON.parse(localStorage.getItem("empDetails"));
empDetails = empDetails.map((empDetail) => {
if (empDetail.id === parseInt(editID)) {
empDetail.name.employeeIdLocal = tr.cells[0].textContent;
empDetail.name.employeeNameLocal = tr.cells[1].textContent;
empDetail.name.designationLocal = tr.cells[2].textContent;
empDetail.name.salaryLocal = tr.cells[3].textContent;
}
return empDetail;
});
localStorage.setItem("empDetails", JSON.stringify(empDetails));
}

Related

Update button not working.(Attached Js fiddle link below)

Actually what I am trying to achieve is when edit button is clicked then all the values of that row will be filled into inputs and the edit button will be converted to a update button and after making some changes when we click the update button the new value should be updated in row.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="container">
<h1>Expense Tracker</h1>
<div id="details">
<select name="type" id="exp-type">
<option value="choose-type">Choose Type</option>
<option value="Debit-Card">Debit Card</option>
<option value="Credit-Card">Credit Card</option>
<option value="Cash">Cash</option>
</select>
<input type="number" id="exp-amount" placeholder="Type Amount...">
<input type="text" id="exp-name" placeholder="Type Expense Name...">
<input type="date" id="exp-date">
<button id="exp-btn">Add Expense</button>
</div>
<div id="data">
<table id="table">
<tr>
<th>Serial</th>
<th>Type</th>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Delete</th>
<th>Edit</th>
</tr>
</table>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
JS
const expAmount = document.getElementById("exp-amount");
const expName = document.getElementById("exp-name");
const expDate = document.getElementById("exp-date");
const expBtn = document.getElementById("exp-btn");
const expType = document.getElementById("exp-type");
const table = document.getElementById("table");
const tableChild = document.getElementById("table").childNodes;
expBtn.addEventListener("click", () => {
const expT = expType.value;
const expN = expName.value;
const expD = expDate.value;
const expA = expAmount.value;
if (expT === "choose-type") {
alert("Please choose the expense type !");
return;
}
const tr = document.createElement("tr");
// Serial No
const td1 = document.createElement("td");
const td1Text = document.createTextNode(tableChild.length - 1);
td1.appendChild(td1Text);
tr.appendChild(td1);
// Expresnse Type
const td2 = document.createElement("td");
const td2Text = document.createTextNode(expT);
td2.appendChild(td2Text);
td2.classList.add("expT-data");
tr.appendChild(td2);
// Expense Name
const td3 = document.createElement("td");
const td3Text = document.createTextNode(expN);
td3.appendChild(td3Text);
td3.classList.add("expN-data");
tr.appendChild(td3);
// Expense Date
const td4 = document.createElement("td");
const td4Text = document.createTextNode(expD);
td4.appendChild(td4Text);
td4.classList.add("expD-data");
tr.appendChild(td4);
// Expense Amount
const td5 = document.createElement("td");
const td5Text = document.createTextNode(expA + " Rs");
td5.appendChild(td5Text);
td5.classList.add("expA-data");
tr.appendChild(td5);
// Delete Btn
const td6 = document.createElement("td");
const td6Text = document.createTextNode("Delete");
td6.append(td6Text);
td6.classList.add("del-btn");
tr.appendChild(td6);
const td7 = document.createElement("td");
const td7Text = document.createTextNode("Edit");
td7.append(td7Text);
td7.classList.add("edit-btn");
tr.appendChild(td7);
table.appendChild(tr);
const editBtn = document.getElementsByClassName("edit-btn");
editFun(editBtn);
const delBtn = document.getElementsByClassName("del-btn");
btnFun(delBtn);
expType.value = expType.children[0].value;
expName.value = "";
expDate.value = "";
expAmount.value = "";
});
// Function for Delete Button
function btnFun(delBtn) {
Array.from(delBtn).forEach((e) => {
e.addEventListener("click", (e) => {
const a = e.currentTarget;
a.parentElement.remove();
});
});
}
// Function for Edit Button
function editFun(editBtn) {
// expN, expD, expA, expT - using this here does not work
Array.from(editBtn).forEach((e) => {
e.addEventListener("click", (ev) => {
const siblings = ev.currentTarget.parentElement.childNodes;
expType.value = siblings[1].innerText;
expName.value = siblings[2].innerText;
expDate.value = siblings[3].innerText;
expAmount.value = siblings[4].innerText.split(" ")[0];
ev.currentTarget.classList.add("update");
ev.currentTarget.innerText = "Update";
// working portion
updateValue(ev, siblings);
});
});
}
// Not working portion
function updateValue(ev, siblings) {
const updateBtn = ev.currentTarget;
if (updateBtn.classList.contains("update")) {
updateBtn.addEventListener("click", () => {
siblings[1].innerText = expType.value;
siblings[2].innerText = expName.value;
siblings[3].innerText = expDate.value;
siblings[4].innerText = expAmount.value + " Rs";
});
}
}
Js fiddle here

Delete table row with JavaScript?

I am adding some data with JavaScript with no problem but I wanted to delete a row by adding delete button inside the row which I add, but I couldn't do it. The code is below. The delete button doesn't work:
const ad = document.querySelector("#ad");
const soyad = document.querySelector("#soyad");
const yas = document.querySelector("#yas");
const ekle = document.querySelector("#ekle");
const liste = document.querySelector("#liste");
ekle.onclick = function() {
let tAd = document.createElement("td");
let tSoyad = document.createElement("td");
let tYas = document.createElement("td");
let tSil = document.createElement("td");
let silBtn = document.createElement("button");
silBtn.textContent = "Sil";
tAd.textContent = ad.value;
tSoyad.textContent = soyad.value;
tYas.textContent = yas.value;
let tr = document.createElement("tr");
tr.appendChild(tAd);
tr.appendChild(tSoyad);
tr.appendChild(tYas);
tr.appendChild(silBtn);
liste.appendChild(tr);
ad.value = "";
soyad.value = "";
yas.value = "";
ad.focus();
}
silBtn.onclick = function(e) {
tr.appendChild(tAd);
tr.appendChild(tSoyad);
tr.appendChild(tYas);
tr.appendChild(silBtn);
liste.removeChild(this.parentNode.parentNode);
}
<div id="sayfa">
<label for="">Ad:</label>
<input type="text" id="ad">
<label for="">Soyad</label>
<input type="text" id="soyad">
<label for="">Yas</label>
<input type="text" id="yas">
<button id="ekle">Tabloya Ekle</button>
<table id="liste">
<tr>
<th>Ad</th>
<th>SoyAd</th>
<th>Yaş</th>
<th>Sil</th>
</tr>
</table>
</div>
Use This Javascript
<script>
const ad=document.querySelector("#ad");
const soyad=document.querySelector("#soyad");
const yas=document.querySelector("#yas");
const ekle=document.querySelector("#ekle");
const liste=document.querySelector("#liste");
ekle.onclick=function(){
let tAd=document.createElement("td");
let tSoyad=document.createElement("td");
let tYas=document.createElement("td");
let tSil = document.createElement("td");
let silBtn =document.createElement("button");
silBtn.textContent="Sil";
tAd.textContent=ad.value;
tSoyad.textContent=soyad.value;
tYas.textContent=yas.value;
let tr=document.createElement("tr");
tr.appendChild(tAd);
tr.appendChild(tSoyad);
tr.appendChild(tYas);
tr.appendChild(silBtn);
liste.appendChild(tr);
ad.value="";
soyad.value="";
yas.value="";
ad.focus();
silBtn.onclick=function(e){
liste.removeChild(this.parentNode);
}
}
</script>

Target and update a specific element in a table with JavaScript

I have an assignment to build a simple static CRUD page using nothing but HTML, CSS, and JavaScript. I'm almost done but I can't for the life of me figure out how to make the update function work.
The idea is to click on the pencil icon and then rewrite whatever is in that field. However, I'm unable to figure out how to expand that functionality to all three fields, it just works on one.
Heres the page. If you click on "cadastrar-se" it will create three "td" with the pencil, but only one works(the one saying "locado?"). Snippets are below but I used localStorage so it won't run properly.
The function of interest is at the bottom of the page, called "updateItems()".
I thank you in advance for any help.
const createTd = item => {
const Td = document.createElement("td");
Td.innerHTML = item;
return Td;
};
const createTdWithI = item => {
const Td = document.createElement("td");
const i = document.createElement("i");
Td.innerHTML = item;
Td.setAttribute("class", "tdEdit");
Td.appendChild(i).setAttribute("class", "fas fa-edit");
return Td;
}
const appendChildren = (parent, children) => {
children.forEach(child => {
parent.setAttribute("class", "tr");
parent.appendChild(child);
});
};
document.querySelector("#addClientBtn").addEventListener("click", () => {
const clientName = document.querySelector("#name").value;
const clientMovie = document.querySelector("#movie").value;
const clientLocado = document.querySelector("#rentStatus").value;
localStorage.setItem("clientName", clientName);
localStorage.setItem("clientMovie", clientMovie);
localStorage.setItem("clientLocado", clientLocado);
const getTbody = document.querySelector("#tbody");
const createTr = document.createElement("tr");
const appendTr = getTbody.appendChild(createTr);
const items = [
createTdWithI(localStorage.getItem("clientName")),
createTdWithI(localStorage.getItem("clientMovie")),
createTdWithI(localStorage.getItem("clientLocado")),
createTd('<i class="fas fa-trash"></i>')
];
appendChildren(appendTr, items);
deleteRow();
updateItems();
});
// Deleta as linhas na tabela
function deleteRow() {
let trashIcon = document.querySelectorAll(".fa-trash");
trashIcon[trashIcon.length - 1].addEventListener("click", event => {
trashIcon = event.target;
trashIcon.parentNode.parentNode.parentNode.removeChild(trashIcon.parentNode.parentNode);
});
}
function updateItems() {
let editIcon = document.querySelectorAll(".fa-edit");
// let targetText = document.querySelectorAll(".tdEdit");
editIcon[editIcon.length - 1].addEventListener("click", event => {
editIcon = event.target;
editIcon.innerText = "test";
// for (let i = 0; i < editIcon.length; i++) {
// editIcon.length = i;
// editIcon[i] = event.target;
// editIcon[i].innerText = "testLocado";
// }
// if (editIcon.length === editIcon.length - 1) {
// editIcon = event.target;
// editIcon.innerText = "testLocado";
// } else if (editIcon.length === editIcon.length - 2) {
// editIcon = event.target;
// editIcon.parentNode.innerText = "testFilme";
// } else if (editIcon.length === editIcon.length - 3) {
// editIcon = event.target;
// editIcon.parentNode.innetText = "testNome";
// }
});
}
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<meta name="author" content="Renan Martineli de Paula" />
<meta name="description" content="locadora de filmes Nova Singular processo seletivo desenvolvimento - sistema" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" integrity="sha384-vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp" crossorigin="anonymous">
<!-- <link type="text/css" rel="stylesheet" href="reset.css" /> -->
<link type="text/css" rel="stylesheet" href="styles.css" />
<script src="sistema.js" defer></script>
<title>Sistema</title>
</head>
<body>
<h1>Bem vindo(a), <span id="userNameWelcome"></span>.
<fieldset>
<legend>Cadastrar cliente</legend>
<label for="name">
<p>Nome</p>
<input type="text" id="name" required />
</label>
<label for="movie">
<p>Filme</p>
<input type="text" id="movie" required />
</label>
<br />
<label for="rentStatus">
<span>Locado?</span>
<select name="locado" id="rentStatus" required>
<option value="Sim">Sim</option>
<option value="Não">Não</option>
</select>
</label>
<br />
<button id="addClientBtn">Cadastrar</button>
</fieldset>
<input type="text" id="searchMenu" placeholder="Procure por clientes"/>
<table id="clientTable">
<thead>
<tr>
<th>Nome</th>
<th>Filme</th>
<th>Locado?</th>
<!-- <th>Modificar</th> -->
<th>Deletar</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</body>
<script>
// Mostra o nome do usuário na tela de boas vindas
document.querySelector("#userNameWelcome").innerHTML = localStorage.getItem("userName");
</script>
</html>
Try this
function updateItems() {
let editIcon = document.querySelectorAll(".fa-edit");
// let targetText = document.querySelectorAll(".tdEdit");
for(let icon of editIcon){
icon.addEventListener('click', (event)=>{
editIcon = event.target;
editIcon.innerText = "test";
}, false);
}

Javascript how do I get values from generated cells in HTML table?

I have a table (check screenshot) where I can generate rows and the second column will contain a number from a text field. I want to be able to grab that number from a generated cell and perform calculations with it. I am not entirely sure how to target the cell that gets generated given I can generate X amount of rows. The principle for this table is to generate numbers from a text field and then press a button and the third column will display a sum of all previous second column values. The execution will start after a button is pressed which I will add later
var counter = 1;
var pNum = 0;
var i;
//Target elements
let btnAdd = document.getElementById('btn');
let testBtn = document.getElementById('test');
let table = document.getElementById('table1');
let bTimeInput = document.querySelector('#bTime')
let bValue = document.querySelector('bCell');
//check for empty value
function checkForEmpty(input) {
if(input.value == null || input.value == undefined || input.value.length == 0) {
return true;
}
return false;
}
btnAdd.addEventListener('click', () => {
if(checkForEmpty(bTimeInput)) {
alert('Enter a number')
} else {
counter++;
pNum++;
let bTime = bTimeInput.value;
let wTime = 'dummyValue';
let taTime = 0;
let template = `
<tr>
<td>${pNum}</td>
<td>${bTime}</td>
<td>${wTime}</td>
</tr>`;
table.innerHTML += template;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>FCFS CPU Scheduling Algorithm</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div id="data">
<input type="number" id="bTime" placeholder="enter burst time">
<button id="btn">Add process</button>
</div>
<table id="table1">
<tr>
<th>P#</th>
<th id="bCell">burst time</th>
<th>wait time</th>
<th>t/a time</th>
</tr>
</table>
</div>
<script src="algorithm.js"></script>
</body>
</html>
So I added some class and row pointers to help out. see what you think.
var counter = 0;
var pNum = 0;
var i;
//Target elements
let btnAdd = document.getElementById('btn');
let testBtn = document.getElementById('test');
let table = document.getElementById('table1');
let bTimeInput = document.querySelector('#bTime')
let bValue = document.querySelector('bCell');
//check for empty value
function checkForEmpty(input) {
if(input.value == null || input.value == undefined || input.value.length == 0) {
return true;
}
return false;
}
const getTotalTime = (bTime, counter) => {
if (counter === 1) return bTime;
const { innerText: pTime } = document.querySelector(`tr.row${counter-1} td.col4`);
return parseInt(bTime, 10) + parseInt(pTime, 10);
};
btnAdd.addEventListener('click', () => {
if(checkForEmpty(bTimeInput)) {
alert('Enter a number')
} else {
counter++;
pNum++;
let bTime = bTimeInput.value;
let wTime = 'dummyValue';
let taTime = 0;
let template = `
<tr class="row${counter}">
<td class="col1">${pNum}</td>
<td class="col2">${bTime}</td>
<td class="col3">${wTime}</td>
<td class="col4">${getTotalTime(bTime, counter)}</td>
</tr>`;
table.innerHTML += template;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>FCFS CPU Scheduling Algorithm</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div id="data">
<input type="number" id="bTime" placeholder="enter burst time">
<button id="btn">Add process</button>
</div>
<table id="table1">
<tr>
<th>P#</th>
<th id="bCell">burst time</th>
<th>wait time</th>
<th>t/a time</th>
</tr>
</table>
</div>
<script src="algorithm.js"></script>
</body>
</html>
Here is a version that takes on board with Chris G mentions about seperation.
var counter = 0;
var pNum = 0;
var i;
const data = {
points: []
};
const headerTemplate = () => `
<tr>
<th>P#</th>
<th id="bCell">burst time</th>
<th>wait time</th>
<th>t/a time</th>
</tr>
`;
const rowTemplate = ({id, bTime, wTime, tTime}) => `
<tr>
<td>${id}</td>
<td>${bTime}</td>
<td>${wTime}</td>
<td>${tTime}</td>
</tr>
`;
//Target elements
let btnAdd = document.getElementById('btn');
let testBtn = document.getElementById('test');
let table = document.getElementById('table1');
let bTimeInput = document.querySelector('#bTime')
let bValue = document.querySelector('bCell');
//check for empty value
function checkForEmpty(input) {
if(input.value == null || input.value == undefined || input.value.length == 0) {
return true;
}
return false;
}
const getTotalTime = (bTime) => {
if (data.points.length === 0) return bTime;
return bTime + data.points[data.points.length-1].tTime;
};
const drawTable = () => data.points.map(point => rowTemplate(point)).join('');
btnAdd.addEventListener('click', () => {
if(checkForEmpty(bTimeInput)) {
alert('Enter a number')
} else {
counter ++;
const bTime = parseInt(bTimeInput.value);
const newDataPoint = {
id: counter,
bTime,
wTime: 'dummyValue',
tTime: getTotalTime(bTime)
};
data.points.push(newDataPoint);
table.innerHTML = headerTemplate() + drawTable(data);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>FCFS CPU Scheduling Algorithm</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div id="data">
<input type="number" id="bTime" placeholder="enter burst time">
<button id="btn">Add process</button>
</div>
<table id="table1">
</table>
</div>
<script src="algorithm.js"></script>
</body>
</html>
The exact answer to your problem cannot be given without code snippets but here is an approach which I thought of:
You can use the
const cells=document.querySelectorAll('td')
to get a node list of all the elements and then target specific cells by indexing this list. Then you can extract value from those node elements by
cells[index].innerText
or
cells[index].innerHTML
and perform operations on it.
var counter = 1;
var pNum = 0;
var i;
//Target elements
let btnAdd = document.getElementById('btn');
let testBtn = document.getElementById('test');
let table = document.getElementById('table1');
let bTimeInput = document.querySelector('#bTime')
let bValue = document.querySelector('bCell');
//check for empty value
function checkForEmpty(input) {
if(input.value == null || input.value == undefined || input.value.length == 0) {
return true;
}
return false;
}
var x0=[]//array for saving
btnAdd.addEventListener('click', () => {
if(checkForEmpty(bTimeInput)) {
alert('Enter a number')
} else {
counter++;
pNum++;
let bTime = bTimeInput.value;
let wTime = 'dummyValue';
let taTime = 0;
//extremely long but successful traceable tags begin
var x1=document.createElement('tr')
table.appendChild(x1)//parent element in proper place
//now to create children
var x2=document.createElement('td')
var x3=document.createElement('td')
var x4=document.createElement('td')
//now to apply data to children
x2.innerText=pNum
x3.innerText=bTime
x4.innerText=wTime
//now to deploy the children
x1.appendChild(x2)
x1.appendChild(x3)
x1.appendChild(x4)
//extremely long but successful traceable tags end
//now to place in array
x0.push({x1:x1,x2:x2,x3:x3,x4:x4})
console.log(x0[x0.length-1])
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>FCFS CPU Scheduling Algorithm</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div id="data">
<input type="number" id="bTime" placeholder="enter burst time">
<button id="btn">Add process</button>
</div>
<table id="table1">
<tr>
<th>P#</th>
<th id="bCell">burst time</th>
<th>wait time</th>
<th>t/a time</th>
</tr>
</table>
</div>
<script src="algorithm.js"></script>
</body>
</html>

How to get tr element using ParentNode

Use the check boxes to display the tasks that have the active button pressed when you click the "In Progress" check, and the completion button when you click the "Complete" check.
I am trying to implement that only the tasks that are present are displayed.
Currently, when the check box is set to "Complete", "Button only" is hidden.
I have tried the following:
const doneTasks = document.getElementsByTagName('tr');
I tried to get the tr element as above, but it didn't work.
I am thinking that if I get the tr element, the entire task will be hidden, while the button element has been obtained to hide it now.
Please tell me to someone.
{
document.addEventListener('DOMContentLoaded', () => {
const addTaskTrigger = document.getElementsByClassName('addTask-trigger')[0];
const addTaskTarget = document.getElementsByClassName('addTask-target')[0];
const addTaskValue = document.getElementsByClassName('addTask-value')[0];
const radioWork = document.getElementById('radio-work');
const radioDone = document.getElementById('radio-done');
let nextId = 0;
const todos = [];
//Taskとidを作成
const addTask = (task, id, tableItem) => {
const idSpanTd = document.createElement('td');
const taskSpanTd = document.createElement('td');
//タスク追加時にtodosにtodoを追加
//要素内のHTML文章を変更する
idSpanTd.innerText = id;
taskSpanTd.innerText = task;
//生成したテーブル要素をブラウザに表示する
tableItem.append(idSpanTd);
tableItem.append(taskSpanTd);
addTaskTarget.append(tableItem);
};
//Button要素を生成する
const addButton = (tableItem, removeButton, createButton) => {
const createButtonTd = document.createElement('td');
const removeButtonTd = document.createElement('td');
//要素内のHTML文章を変更する
createButton.innerText = '作業中';
removeButton.innerText = '削除';
//生成したテーブル要素をブラウザに表示する
tableItem.append(createButtonTd);
tableItem.append(removeButtonTd);
addTaskTarget.append(tableItem);
//生成したbutton要素を生成する
createButtonTd.append(createButton);
removeButtonTd.append(removeButton);
};
//追加ボタンをクリックした際にtd要素を追加する処理を行う
addTaskTrigger.addEventListener('click', () => {
const task = addTaskValue.value;
const tableItem = document.createElement('tr');
const removeButton = document.createElement('button');
const createButton = document.createElement('button');
addTask(task, nextId++, tableItem);
addButton(tableItem, removeButton, createButton);
addTaskValue.value = '';
// //削除ボタンを押した時にタスクを削除する
const deleteElement = (a) => {
const tableTag = a.target.closest('tr');
if (tableTag) tableTag.remove();
updateId();
}
removeButton.addEventListener('click', deleteElement, false);
//ボタンを押したら作業中、完了中と変わる
createButton.addEventListener('click', (a) => {
if (createButton.textContent === "作業中") {
createButton.textContent = "完了";
const doneParent = a.target.parentNode;
doneParent.className = 'workDone';/*完了class*/
} else {
createButton.textContent = "作業中";
const workParent = a.target.parentNode;
workParent.className = 'work';/*作業中class*/
}
});
})
//todoの状態を管理
const todo = [{task: 'taskSpanTd',status: '作業中'},{task: 'taskSpanTd',status: '完了'}]
todos.push(todo);
/*ラジオボタン作業中を押下時の処理*/
radioDone.addEventListener('click', function () {
let workTasks = document.getElementsByClassName('work');
workTasks = Array.from(tr);
if (radioWork.checked.tr=== true) {
workTasks.forEach(function (workTasks) {
workTasks.style.display = "";
})
} else {
workTasks.forEach(function (workTasks) {
workTasks.style.display = "none";
})
}
})
// ラジオボタン完了押下時処理
radioWork.addEventListener('click', function () {
let doneTasks = document.getElementsByClassName('workDone');
doneTasks = Array.from(tr);
if (radioDone.checked.tr === true) {
doneTasks.forEach(function (doneTasks) {
doneTasks.style.display = "";
})
} else {
doneTasks.forEach(function (doneTasks) {
doneTasks.style.display = "none";
})
}
})
// 連番 再振り直し
const updateId = () => {
const tbody = document.getElementsByTagName("tbody")[0];
const taskList = tbody.getElementsByTagName('tr');
nextId = 0;
Array.from(taskList, tr => {
tr.getElementsByTagName('td')[0].textContent = nextId;
nextId++
});
}
});
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>Todoリスト</title>
</head>
<body>
<h1>Todoリスト</h1>
<p>
<input type="radio" name="task" value="1" checked ="checked">全て
<input type="radio" id="radio-work" name="task" value="2">作業中
<input type="radio" id="radio-done" name="task" value="3">完了
</p>
<p></p>
<table>
<thead>
<th>ID</th>
<th>コメント</th>
<th>状態</th>
<th></th>
</thead>
<tbody class="addTask-target" id="tbody"></tbody>
</table>
<h2>新規タスクの追加</h2>
<input class="addTask-value" type="text" />
<button class="addTask-trigger" type="button">追加</button>
<script src="js/main.js"></script>
</body>
</html>
It's not good idea to select the tr tag by using it parent for example you can select child elements of div like
var div = document.getElementById('parent');
div.firstElementChild.style.background = 'red';
div.lastElementChild.style.background = 'blue';
#parent {
width: 100px;
height: 100px;
position: relative;
}
.child {
width: 100%;
height: 50%;
}
<div id="parent">
<div class="child"></div>
<div class="child"></div>
</div>
but this can't be done on table if you you do it you will not point only one tr it will be applied on all tr like the following example
table = document.getElementsByTagName('table')[0];
table.firstElementChild.style.background = 'grey';
table.lastElementChild.style.background = 'green';
<table border="1px" cellpadding="5px">
<tr>
<th>Names</th>
</tr>
<tr>
<td>Eric</td>
</tr>
<tr>
<td>Ivan</td>
</tr>
</table>
so better select all table row in table and loop on the to get one by one like
tr = document.getElementsByTagName('tr');
for (var i = 0; i < tr.length; i++) {
if (i == 0) {
tr[i].style.background = 'green';
} else if (i == 1) {
tr[i].style.background = 'grey';
} else {
tr[i].style.background = 'cyan';
}
}
<table border="1px" cellpadding="5px">
<tr>
<th>Names</th>
</tr>
<tr>
<td>Eric</td>
</tr>
<tr>
<td>Ivan</td>
</tr>
</table>

Categories

Resources