push created object with class into array - javascript

I ran into this problem with my code.
I want to push the created objects into an array and then display them.
The problem is that the newly created object are overwrite the old ones, I still have issues with pushing objects into array.
My aim is to create inputs and grab their values and through classes I create object then push them into array, loop and display them on the screen.
<!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>Document</title>
</head>
<body>
<input type="text" id="title" />
<input type="text" id="author" />
<input type="number" id="pages" />
<h1>title :</h1>
<h2>Author :</h2>
<h3>Pages :</h3>
<button>Submit</button>
<script src="app.js"></script>
</body>
</html>
const title = document.querySelector("#title");
const author = document.querySelector("#author");
const pages = document.querySelector("#pages");
const submit = document.querySelector("button");
const h1 = document.querySelector("h1");
const h2 = document.querySelector("h2");
const h3 = document.querySelector("h3");
let myLibrary = [];
let Book = class {
constructor(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
this.words = [];
}
};
submit.addEventListener("click", () => {
if (title.value === "" || author.value === "" || pages.value === "") {
return;
}
if (title.value && author.value && pages.value) {
myLibrary.push(new Book(title.value, author.value, pages.value));
}
title.value = "";
author.value = "";
pages.value = "";
myLibrary.forEach((e) => {
h1.innerHTML = e.title;
h2.innerHTML = e.author;
h3.innerHTML = e.pages;
});
console.log(myLibrary);
});

So here I create list items for each book in the array. I have an empty string and I add alle the books to it and override the <ul> in the end.
const book = document.forms.book;
const books = document.getElementById('books');
let myLibrary = [];
const Book = class {
constructor(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
this.words = [];
}
};
book.addEventListener("submit", e => {
e.preventDefault();
myLibrary.push(new Book(e.target.title.value, e.target.author.value, e.target.pages.value));
e.target.reset();
let str = '';
myLibrary.forEach(book => {
str += `<li>${book.title}, ${book.author}, ${book.pages}</li>`;
});
books.innerHTML = str;
});
<form name="book">
<lable>Title: <input name="title" type="text" required></lable>
<lable>Author: <input name="author" type="text" required></lable>
<lable>Pages: <input name="pages" type="text" required></lable>
<button>Save</button>
</form>
<ul id="books"></ul>

You insert the info of each book on the same elements (h1,h2,h3)
I suggest you create a container and new h1,h2,h3 for each book:
//You can ommit the forEach, so the below elements are created only for the last added book, not all the books.
// or you can empty the main books list container (here body), then do the forEach and create below elements for all books every time (not good performance wise)
submit.addEventListener("click", () => {
if (title.value === "" || author.value === "" || pages.value ===
"") {
return;
}
if (title.value && author.value && pages.value) {
myLibrary.push(new Book(title.value, author.value, pages.value));
}
let container=document.createElement("div")
let titleDisplayer=document.createElement("h1")
let authorDisplayer=document.createElement("h2")
let pagesDisplayer=document.createElement("h3")
titleDisplayer.innerHTML = title.value;
authorDisplayer.innerHTML = author.value;
pagesDisplayer.innerHTML = pages.value;
container.append(titleDisplayer,authorDisplayer,pagesDisplayer)
document.body.append(container)
title.value = "";
author.value = "";
pages.value = "";
console.log(myLibrary);
});

Related

How to reload current page without losing added list items?

I'm creating something similar to a to-do-list project, but whenever I refresh the page I lose all the added items, I've tried using:
`
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
`
but still it doesn't work, I may have used it in the wrong place or wrong way. any help please?
here is my full code:
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" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<title>To Do List</title>
</head>
<body>
<section class="section-center">
<form class="todolist-form">
<h3>To Do List!</h3>
<div class="input-button">
<input type="text" id="items-input" placeholder="e.g. eggs" />
<input
type="button"
class="submit-btn"
onclick="addItems()"
value="Submit"
/>
</div>
<div class="added-items">
<ul id="faves"></ul>
</div>
</form>
</section>
<script src="main.js"></script>
</body>
</html>
`
Javascript:
`
function addItems() {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
var input = document.getElementById("items-input");
li.innerHTML = input.value;
input.value = "";
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
/*********/
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
}
`
What am I doing wrong? I've included jQuery's CDN too, but still it doesn't work.
var texts = [];
function addItems() {
var input = document.getElementById("items-input");
createElement(input.value)
input.value = "";
}
function createElement(value) {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
li.innerHTML = value;
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
texts.push(value)
}
window.onbeforeunload = function () {
// Store text array in storage
localStorage.setItem("list", JSON.stringify(texts));
};
window.onload = function () {
// get list grom storage
var list = localStorage.getItem("list");
if (list !== null) {
list = JSON.parse(list)
for (let index = 0; index < list.length; index++) {
const element = list[index];
// create your dom element
createElement(element)
}
}
};
Using an Array to manage the data flow. This will do the job but still a mess.
Try adding event listeners once and outside of your function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list")
};
function addItems() {
...
}
Assuming that $("#listItem").val() will return the data you want, place below block outsite of the addItems() function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};

How to store task in localstorage than onload make it appear in individual tasks

I am trying to make a To Do list but I have encountered a problem with storing it in local storage. I have tried storing the task in a var than it in localStorage but than when a new task is added it overwrites the variable and when I tried to store it in array and than when I tried to retrieve it from array all tasks appeared in a single task div. I want to store the tasks in local storage and have the task be edited, deleted, marked done also for localStorage too. I am providing the code.
<--JS-->
let tasksDiv = document.getElementById("tasks");
let oldTasksDiv = document.getElementById("old-tasks");
let input = document.getElementById('input');
var clear = document.getElementById('clear');
input.value = "What do you have planned?";
addBtn.addEventListener('click' , onclickBtn);
input.addEventListener('keypress' , function(){
if(event.keyCode === 13){
onclickBtn();
}
});
input.addEventListener('click' , function (){
if(input.value === "What do you have planned?"){
input.value ="";
}
})
clear.addEventListener('click' , function (){
input.value ="";
})
function onclickBtn(){
if(input.value.length !== 0){
var tasksName = document.createElement('div');
tasksName.classList.add("tasks-div")
var task = document.createElement('p');
task.innerText = input.value;
task.classList.add("task");
var del = document.createElement('button');
del.classList.add("del");
del.innerHTML = '<i class="fas fa-solid fa-trash"></i>';
var edit = document.createElement('button');
edit.classList.add("edit");
edit.innerHTML = '<i class="fas fa-solid fa-pen-to-square"></i>';
var save = document.createElement('button');
save.classList.add("save");
save.innerHTML = '<i class="fas fa-solid fa-floppy-disk"></i>';
var chkbox = document.createElement('input');
chkbox.classList.add("chkbox")
chkbox.type = "checkbox";
tasksName.appendChild(chkbox);
tasksName.appendChild(task);
tasksName.appendChild(del);
tasksName.appendChild(edit);
tasksName.appendChild(save);
tasksDiv.appendChild(tasksName);
chkbox.addEventListener('click' , function(){
if(chkbox.checked === true){
task.style.textDecoration = "line-through red";
edit.style.display = "none";
save.style.display = "none";
}
else{
task.style.textDecoration = "none";
edit.style.display = "block";
}
})
del.addEventListener('click' , function(){
tasksDiv.removeChild(tasksName);
})
edit.addEventListener('click' , function(){
task.contentEditable = true;
task.focus();
edit.style.display = "none";
save.style.display = "block";
})
save.addEventListener('click' , function(){
if(task.innerHTML === '<br>'){
alert('This task will be deleted');
tasksDiv.removeChild(tasksName);
}
task.contentEditable = false;
task.blur();
edit.style.display = "block";
save.style.display = "none";
})
}
else{
alert("Please enter a task");
}
}
<-- 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">
<title>Tasks Keeper</title>
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./css/resp.css">
<script src="https://kit.fontawesome.com/6bf6193572.js" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/9b41c17796.js" crossorigin="anonymous"></script>
</head>
<body>
<header>
<div class="brand-div">
<h1><span class="brand">Tasks Keeper</span></h1>
<span class="made-by">Made By Raghav Srvt</span>
</div>
<div class="input-div">
<div class="input-div-clear">
<input type="text" placeholder="What do you have planned?" id="input" value="What do you have planned?">
<i class="fa-solid fa-xmark" id="clear"></i>
</div>
<button type="submit" id="add-btn">Add</button>
</div>
</header>
<div id="tasks">
</div>
<script src = "./app.js"></script>
</body>
</html>
You can insert todos as object into an Array and store it on LocalStorage.
It is a Functionality that makes it Easy for you.
function LsHandling() {
return {
get: function (key) {
const item = localStorage.getItem(key);
if (item) {
return JSON.parse(item);
}
},
set: function (todo, key) {
const item = localStorage.getItem(key);
if (item) {
const itemToArray = [...JSON.parse(item)];
for (data in itemToArray) {
if (itemToArray[data].id === todo.id) {
return;
} else {
itemToArray.push(todo)
localStorage.setItem(key, JSON.stringify(itemToArray));
}
}
} else {
const defaultArray = [todo];
localStorage.setItem(key, JSON.stringify(defaultArray));
}
},
};
}
And you can use it Like This :
for getting the todosArray : LsHandling().get(yourKey)
for setting a todo in todosArray : LsHandling().set(todoObject, yourKey)
Note : for deleting or editing todos , you must define an id for each todo

Using PokeAPI to fetch data. Can't figure out why span element is not updating

So I'm using the PokeAPI to fetch the name of a Pokemon, then shuffling that name, and the user is supposed to guess what it is in the input. If they don't know then they can click the next button and it reshuffles a new mon. If they guess right they can press the same next button for a new mon. Each time they guess right the score increases by 1. That's working but I cant figure out why the out of/total games span isn't updating as well. Please excuse my terrible attempt at JS I'm very new if you can help me make my code look better that would be great.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="style.css" />
<title>Who's that Pkmn?</title>
</head>
<body>
<header>
<h1>Who's that Pokemon?!</h1>
</header>
<div id="jumble">?????</div>
<div class="container">
<input id="guess" type="text" placeholder="enter pkmn name" />
<button id="submit" class="btn" type="submit">go</button>
<button id="next" class="btn">next</button>
<p id="msg">unshuffle the letters</p>
</div>
<div id="scorekeepers">
<p>Score: <span id="score">0</span>
out of: <span id="gamesPlayed">0</span></p>
</div>
<script src="script.js"></script>
</body>
</html>
let jumbledName = document.querySelector("#jumble");
let guessInput = document.querySelector('#guess')
let submitButton = document.querySelector('#submit')
let nextButton=document.querySelector('#next')
let messageDisplay = document.querySelector('#msg')
let score = document.querySelector('#score')
let gamesPlayed = document.querySelector('#gamesPlayed')
score = 0;
gamesPlayed = 0;
let getPokemonName = function() {
fetch(`https://pokeapi.co/api/v2/pokemon/${Math.floor(Math.random()*151+1)}/`)
.then(function(response) {
return response.json();
})
.then(function(data) {
const pokeName = data.name;
const pokeNameJumbled = pokeName.shuffle();
displayInfomation(pokeName, pokeNameJumbled);
});
};
getPokemonName();
guessInput.value=''
// pokeNameJumbled=''
const displayInfomation = function(name, jumbledName) {
pokeName = name;
pokeNameJumbled = jumbledName;
jumble.textContent = jumbledName;
};
const displayMessage = function(message) {
document.querySelector("#msg").textContent = message;
};
const checkName = function () {
document.querySelector("#guess").textContent = guessInput;
const guess = document.querySelector("#guess").value.toLowerCase();
if (!guess) {
displayMessage("No guess entered!");
} else if (guess === pokeName) {
displayMessage(`Thats correct! It's ${pokeName}!`)
score++
document.querySelector("#score").textContent = score;
guessInput.value=''
} else if (guess != pokeName) {
displayMessage(`Wrong!`);
document.querySelector("#gamesPlayed").textContent = gamesPlayed;
}
};
submitButton.addEventListener('click', checkName)
nextButton.addEventListener('click',getPokemonName)
String.prototype.shuffle = function() {
var a = this.split(""),
n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
};

How can I replace element afer another query?

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>

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

Categories

Resources