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
Related
i try to do this: Create a web page using HTML and JavaScript. On the website where your name will appear. · Fill in a table with Student Objects. · These objects have 3 fields (fullname, age, amka). The creation of these objects will be done using Constructor (Note the fullname field is the name and is given as follows: "First name - Last name" · The table that is filled until an object is given under the age of 18. ATTENTION this object does not will be inserted in the table.
<!DOCTYPE html>
<html lang="en">
<script>
function createPerson() {
var fullname = document.getElementById('inputValueFullname').value;
var age = document.getElementById('inputValueAge').value;
var amka = document.getElementById('inputValueAmka').value;
function person(fullname, age, amka) {
this.fullname = fullname;
this.age = age;
this.amka = amka;
}
var myArray = [];
var NewPerson = new person(fullname, age, amka);
if(age && age>= 18 && fullname && amka){
myArray.push(NewPerson)
} else {
}
console.log(NewPerson);
}
</script>
<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>
</head>
<body>
<label>Fullname: <input type="text" id="inputValueFullname"></label>
<label>Age:<input type="text" id="inputValueAge"></label>
<label>Amka:<input type="text" id="inputValueAmka"></label>
<button type="button" onclick=" createPerson();">Add</button>
<table id="table">
<thead>
<tr>
<th>Name/Surname</th>
<th>Age</th>
<th>AMKA</th><br><br><br><br><br>
</tr>
</thead>
</table>
</body>
</html>
First off, I assume AMKA is an identification number as when i tried searching what is that about and the only result i got was a company or a greek citizen ID. The JavaScript function to print data to table can be done without using any array.
<script>
function publishToTable() {
const fullname = document.getElementById('fullname').value;
const age = document.getElementById('age').value;
const amka = document.getElementById('amka').value;
const error = document.getElementById('error');
if (age && age>= 18 && fullname && amka) {
const tableElement = document.getElementById('table');
const trElement = document.createElement('tr');
const tbodyElement = document.createElement('tbody');
const fullnameEle = document.createElement('td');
const ageEle = document.createElement('td');
const amkaEle = document.createElement('td');
fullnameEle.innerHTML = fullname;
ageEle.innerHTML = age;
amkaEle.innerHTML = amka;
trElement.appendChild(fullnameEle);
trElement.appendChild(ageEle);
trElement.appendChild(amkaEle);
tbodyElement.appendChild(trElement);
tableElement.appendChild(tbodyElement);
}
}
</script>
I think i fixed your issue:
js_issue_solved.html
Full Code:
// <!DOCTYPE html>
<html lang="en">
<script>
function publishToTable() {
const fullname = document.getElementById('fullname').value;
const age = document.getElementById('age').value;
const amka = document.getElementById('amka').value;
const error = document.getElementById('error');
if (age && age>= 18 && fullname && amka) {
const tableElement = document.getElementById('table');
const trElement = document.createElement('tr');
const tbodyElement = document.createElement('tbody');
const fullnameEle = document.createElement('td');
const ageEle = document.createElement('td');
const amkaEle = document.createElement('td');
fullnameEle.innerHTML = fullname;
ageEle.innerHTML = age;
amkaEle.innerHTML = amka;
trElement.appendChild(fullnameEle);
trElement.appendChild(ageEle);
trElement.appendChild(amkaEle);
tbodyElement.appendChild(trElement);
tableElement.appendChild(tbodyElement);
}
}
</script>
<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></title>
</head>
<body>
<div class="complete">
<div class="form">
<label>Fullname: <input id="fullname" type="text"></label>
<label>Age: <input id="age" type="number"></label>
<label>AMKA: <input id="amka" type="text"></label>
<span id="error"></span>
<button onclick="publishToTable()">Submit</button>
</div>
<div id="tables">
<table id="table">
<thead>
<tr>
<th>|Name/Surname| </th>
<th>|Age| </th>
<th>|AMKA| </th><br><br><br><br><br>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
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));
}
I am writing simple JS app that shows weather. After first query variables like searchTerm or every variable from array are appends to the specific element. But after another query they are not override but added next to the previous one. How can i fix that? Should I use innerHTML or just refresh the page after another API call?
const form = document.querySelector('#searchForm');
const currentTemp = document.querySelector('#temp');
const feelingTemp = document.querySelector('#feelingTemp');
const button = document.querySelector('button');
const img = document.createElement('img');
const searchCity = document.querySelector('#searchingCity');
const sky = document.querySelector('#skyStatus');
const bg_image = document.querySelector('.left-container');
const moreInfo = document.querySelector('.right-container');
const getWeather = async () => {
try{
const searchTerm = form.elements.query.value
const res = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${searchTerm}&units=metric&appid=3861eeae573a8188b76a2d6c0ceccfb9`)
let getTemp = res.data.main.temp,
getFeelsTemp = res.data.main.feels_like,
getTempMin = res.data.main.temp_min,
getTempMax = res.data.main.temp_max,
getPressure = res.data.main.pressure,
getHumidity = res.data.main.humidity;
getSkyIcon = res.data.weather[0].main
searchCity.append(searchTerm)
form.elements.query.value = '';
return [getTemp, getFeelsTemp, getTempMin, getTempMax, getPressure, getHumidity, getSkyIcon]
} catch (e){
return "WEATHER SERVICE IS DOWN :("
}
}
const runApp = async () => {
form.addEventListener('submit', async function (e) {
e.preventDefault()
const [resTemp, resFeelsTemp, resTempMin, resTempMax, resPressure, resHumidity, resSkyIcon] = await getWeather()
// Głowny kontener informacyjny
currentTemp.append(`${Math.floor(resTemp)}°C`)
if(resSkyIcon === 'Clear'){
img.src = "./img/sun.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/sunny_bg.jpg')"
}else if(resSkyIcon === 'Clouds'){
img.src = "./img/cloud.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/cloud_bg.jpg')"
}else{
img.src = "./img/rain.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/rain_bg.jpg')"
}
// Right box
const array = [
`Feels temp ${Math.floor(resFeelsTemp)}°C`,
`Temp min ${Math.floor(resTempMin)}°C`,
`Temp max ${Math.floor(resTempMax)}°C`,
`Pressure ${resPressure}HPa`,
`Humidity ${resHumidity}%`
]
const ul = document.querySelector('ul');
array.forEach((value) =>{
const li = document.createElement('li');
li.innerText = value
ul.appendChild(li)
})
})
}
runApp();
<!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">
<title>WeatherApp - Rob</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="left-container">
<div class="form-container">
<form id="searchForm">
<input type="text" placeholder="Weather in" name="query" id="searchInput">
</form>
</div>
<div class="weather-output">
<h2 id="temp"></h2>
<h2 id="searchingCity"></h2>
<h2 id="skyStatus"></h2>
</div>
<div class="right-container">
<h2 id="right-header">Informacje dodatkowe</h2>
<div class="more-info-container">
<ul></ul>
</div>
</div>
</div>
<script src="./app2.js"></script>
</body>
</html>
You need to clear result that you get before
Just add:
searchCity.innerHTML = '';
...
currentTemp.innerHTML = '';
....
ul.innerHTML = '';
const form = document.querySelector('#searchForm');
const currentTemp = document.querySelector('#temp');
const feelingTemp = document.querySelector('#feelingTemp');
const button = document.querySelector('button');
const img = document.createElement('img');
const searchCity = document.querySelector('#searchingCity');
const sky = document.querySelector('#skyStatus');
const bg_image = document.querySelector('.left-container');
const moreInfo = document.querySelector('.right-container');
const getWeather = async () => {
try{
const searchTerm = form.elements.query.value
const res = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${searchTerm}&units=metric&appid=3861eeae573a8188b76a2d6c0ceccfb9`)
let getTemp = res.data.main.temp,
getFeelsTemp = res.data.main.feels_like,
getTempMin = res.data.main.temp_min,
getTempMax = res.data.main.temp_max,
getPressure = res.data.main.pressure,
getHumidity = res.data.main.humidity;
getSkyIcon = res.data.weather[0].main
searchCity.innerHTML = '';
searchCity.append(searchTerm)
form.elements.query.value = '';
return [getTemp, getFeelsTemp, getTempMin, getTempMax, getPressure, getHumidity, getSkyIcon]
} catch (e){
return "WEATHER SERVICE IS DOWN :("
}
}
const runApp = async () => {
form.addEventListener('submit', async function (e) {
e.preventDefault()
const [resTemp, resFeelsTemp, resTempMin, resTempMax, resPressure, resHumidity, resSkyIcon] = await getWeather()
// Głowny kontener informacyjny
currentTemp.innerHTML = '';
currentTemp.append(`${Math.floor(resTemp)}°C`)
if(resSkyIcon === 'Clear'){
img.src = "./img/sun.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/sunny_bg.jpg')"
}else if(resSkyIcon === 'Clouds'){
img.src = "./img/cloud.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/cloud_bg.jpg')"
}else{
img.src = "./img/rain.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/rain_bg.jpg')"
}
// Right box
const array = [
`Feels temp ${Math.floor(resFeelsTemp)}°C`,
`Temp min ${Math.floor(resTempMin)}°C`,
`Temp max ${Math.floor(resTempMax)}°C`,
`Pressure ${resPressure}HPa`,
`Humidity ${resHumidity}%`
]
const ul = document.querySelector('ul');
ul.innerHTML = '';
array.forEach((value) =>{
const li = document.createElement('li');
li.innerText = value
ul.appendChild(li)
})
})
}
runApp();
<!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">
<title>WeatherApp - Rob</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="left-container">
<div class="form-container">
<form id="searchForm">
<input type="text" placeholder="Weather in" name="query" id="searchInput">
</form>
</div>
<div class="weather-output">
<h2 id="temp"></h2>
<h2 id="searchingCity"></h2>
<h2 id="skyStatus"></h2>
</div>
<div class="right-container">
<h2 id="right-header">Informacje dodatkowe</h2>
<div class="more-info-container">
<ul></ul>
</div>
</div>
</div>
<script src="./app2.js"></script>
</body>
</html>
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);
}
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>