Delete button in To Do List (HTML/JS) - javascript

Recently, I've started to learn html/css/javascript. Although I know some basic stuff I still struggle
with understanding some of the script parts.
I 've created a To Do List but its not finished yet. I'd like to add a button that deletes task but it does not work.
Can someone help me with delete button script part and explain in few words how it should work? This button is ruining everything, I am trying to fix it for five hours but it still doesn't work.
Here is my html code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="./style1.css" />
</head>
<body>
<div class="todo-cat">
<form class="todo-form" id="todoForm">
<div class="todo-form-row">
<label class="todo-form-label" for="todoMessage"
>Podaj treść zadania</label
>
<textarea
class="todo-form-message"
name="todoMessage"
id="todoMessage"
></textarea>
</div>
<div class="todo-form-row">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
<section class="todo-list-cat">
<header class="todo-list-header">
<h2 class="todo-list-title">Lista zadań</h2>
<form class="todo-list-search form">
<input type="search" id="todoSearch" class="todo-list-search" />
</form>
</header>
<div class="todo-list" id="todoList"></div>
</section>
</div>
And here is Script part :
<script>
let todoList = null;
let todoForm = null;
let todoSearch = null;
function addTask(text) {
//element todo
const todo = document.createElement("div");
todo.classList.add("todo-element");
//belka gorna
const todoBar = document.createElement("div");
todoBar.classList.add("todo-element-bar");
//data w belce
const todoDate = document.createElement("div");
todoDate.classList.add("todo-element-var");
const date = new Date();
const dateText = `${date.getDate()} - ${
date.getMonth() + 1
} - ${date.getFullYear()} godz.: ${date.getHours()}:${date.getMinutes()}`;
todoDate.innerText = dateText;
//przycisk usuwania
const todoDelete = document.createElement("button");
todoDelete.classList.add("todo-element-delete");
todoDelete.classList.add("button");
todoDelete.innerHTML = `<i class="fas fa-times-circle"></1>`;
//wrzucamy elementy do belki
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
//element z tekstem
const todoText = document.createElement("div");
todoText.classList.add("todo-element-text");
todoText.innerHTML = text;
//łączymy całość
todo.appendChild(todoBar);
todo.appendChild(todoText);
//wrzucamy do listy
todoList.append(todo);
}
document.addEventListener("DOMContentLoaded", () => {
todoList = document.querySelector("#todoList");
todoForm = document.querySelector("#todoForm");
todoSearch = document.querySelector("todoSearch");
todoForm.addEventListener("submit", (e) => {
e.preventDefault();
const textarea = todoForm.querySelector("textarea");
if (textarea.value != "") {
addTask(textarea.value);
textarea.value = "";
}
});
});
</script>
<script
defer
src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"
></script>
</body>
</html>

This should fix your problem. I've added an event listener to the delete button, then found the parent element on click and then removed it.
let todoList = null;
let todoForm = null;
let todoSearch = null;
function addTask(text) {
//element todo
const todo = document.createElement("div");
todo.classList.add("todo-element");
//belka gorna
const todoBar = document.createElement("div");
todoBar.classList.add("todo-element-bar");
//data w belce
const todoDate = document.createElement("div");
todoDate.classList.add("todo-element-var");
const date = new Date();
const dateText = `${date.getDate()} - ${
date.getMonth() + 1
} - ${date.getFullYear()} godz.: ${date.getHours()}:${date.getMinutes()}`;
todoDate.innerText = dateText;
//przycisk usuwania
const todoDelete = document.createElement("button");
todoDelete.classList.add("todo-element-delete");
todoDelete.classList.add("button");
todoDelete.innerHTML = `delete`;
todoDelete.addEventListener("click", function() {
this.closest(".todo-element").remove()
});
//wrzucamy elementy do belki
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
//element z tekstem
const todoText = document.createElement("div");
todoText.classList.add("todo-element-text");
todoText.innerHTML = text;
//łączymy całość
todo.appendChild(todoBar);
todo.appendChild(todoText);
//wrzucamy do listy
todoList.append(todo);
}
document.addEventListener("DOMContentLoaded", () => {
todoList = document.querySelector("#todoList");
todoForm = document.querySelector("#todoForm");
todoSearch = document.querySelector("todoSearch");
todoForm.addEventListener("submit", (e) => {
e.preventDefault();
const textarea = todoForm.querySelector("textarea");
if (textarea.value != "") {
addTask(textarea.value);
textarea.value = "";
}
});
});
<div class="todo-cat">
<form class="todo-form" id="todoForm">
<div class="todo-form-row">
<label class="todo-form-label" for="todoMessage">Podaj treść zadania</label
>
<textarea
class="todo-form-message"
name="todoMessage"
id="todoMessage"
></textarea>
</div>
<div class="todo-form-row">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
<section class="todo-list-cat">
<header class="todo-list-header">
<h2 class="todo-list-title">Lista zadań</h2>
<form class="todo-list-search form">
<input type="search" id="todoSearch" class="todo-list-search" />
</form>
</header>
<div class="todo-list" id="todoList"></div>
</section>
</div>

Just add an onclick remove() event under your const todoDelete = document.createElement("button");
todoDelete.onclick = function () {
this.parentNode.parentNode.remove();
};
Now to explain how it works:
The button is 'this', the parentNode is the element above, the entire TODO item is two layers above and remove() will delete that one.
(This is your current structure, it is dependent on it)
<div class="todo-element">
<div class="todo-element-bar">
<div class="todo-element-var">3 - 9 - 2020 godz.: 14:28</div>
<button class="todo-element-delete button">BUTTON IS HERE</button>
</div>
<div class="todo-element-text">zrdz</div>
</div>
let todoList = null;
let todoForm = null;
let todoSearch = null;
function addTask(text) {
//element todo
const todo = document.createElement("div");
todo.classList.add("todo-element");
//belka gorna
const todoBar = document.createElement("div");
todoBar.classList.add("todo-element-bar");
//data w belce
const todoDate = document.createElement("div");
todoDate.classList.add("todo-element-var");
const date = new Date();
const dateText = `${date.getDate()} - ${
date.getMonth() + 1
} - ${date.getFullYear()} godz.: ${date.getHours()}:${date.getMinutes()}`;
todoDate.innerText = dateText;
//przycisk usuwania
const todoDelete = document.createElement("button");
todoDelete.onclick = function () {
this.parentNode.parentNode.remove();
};
todoDelete.classList.add("todo-element-delete");
todoDelete.classList.add("button");
todoDelete.innerHTML = `<i class="fas fa-times-circle"></1>`;
//wrzucamy elementy do belki
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
//element z tekstem
const todoText = document.createElement("div");
todoText.classList.add("todo-element-text");
todoText.innerHTML = text;
//łączymy całość
todo.appendChild(todoBar);
todo.appendChild(todoText);
//wrzucamy do listy
todoList.append(todo);
}
document.addEventListener("DOMContentLoaded", () => {
todoList = document.querySelector("#todoList");
todoForm = document.querySelector("#todoForm");
todoSearch = document.querySelector("todoSearch");
todoForm.addEventListener("submit", (e) => {
e.preventDefault();
const textarea = todoForm.querySelector("textarea");
if (textarea.value != "") {
addTask(textarea.value);
textarea.value = "";
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="./style1.css" />
</head>
<body>
<div class="todo-cat">
<form class="todo-form" id="todoForm">
<div class="todo-form-row">
<label class="todo-form-label" for="todoMessage">Podaj treść zadania</label
>
<textarea
class="todo-form-message"
name="todoMessage"
id="todoMessage"
></textarea>
</div>
<div class="todo-form-row">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
<section class="todo-list-cat">
<header class="todo-list-header">
<h2 class="todo-list-title">Lista zadań</h2>
<form class="todo-list-search form">
<input type="search" id="todoSearch" class="todo-list-search" />
</form>
</header>
<div class="todo-list" id="todoList"></div>
</section>
</div>
<script
defer
src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"
></script>
</body>
</html>

Related

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>

Append Element using DOM manipulation cannot loop through using querySelector

I'm trying to loop through the element that i create using DOM manipulation. it was successfully reflected in the html page but when i loop through in it using queryselector, its not looping. I also tried using getElementByClassName and still not looping.
here is the part of the code which I'm pointing out:
I also attached the whole javascript code with html for reference:
const selected = document.querySelector(".selected");
const optionsContainer = document.querySelector(".options-container");
window.addEventListener('DOMContentLoaded', () => {
createNewOption1();
createNewOption2();
});
const optionsList = document.querySelectorAll(".option");
selected.addEventListener("click", () => {
optionsContainer.classList.toggle("active");
});
optionsList.forEach(o => {
o.addEventListener("click", () => {
selected.innerHTML = o.querySelector("label").innerHTML;
optionsContainer.classList.remove("active");
});
});
const createNewOption1 = () => {
const div1 = document.createElement('div');
const input1 = document.createElement('input');
const label1 = document.createElement('label');
div1.className = 'option';
input1.type = 'radio';
input1.className = 'radio';
input1.name = 'category';
label1.htmlFor = 'Rejuvenating';
label1.innerHTML = 'Rejuvenating Set';
div1.appendChild(input1);
div1.appendChild(label1);
optionsContainer.appendChild(div1);
}
const createNewOption2 = () => {
const div2 = document.createElement('div');
const input2 = document.createElement('input');
const label2 = document.createElement('label');
div2.className = 'option';
input2.type = 'radio';
input2.className = 'radio';
input2.name = 'category';
label2.htmlFor = 'Maintenance';
label2.innerHTML = 'Maintenance Set';
div2.appendChild(input2);
div2.appendChild(label2);
optionsContainer.appendChild(div2);
}
<!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>Database Project</title>
<script src="https://kit.fontawesome.com/d6307e6979.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h2>Sales</h2>
<div class="select-box">
<div class="options-container">
</div>
<div class="selected">
<p>Select Item</p>
</div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
You're creating the options in the DOMContentLoaded event listener. But you're calling querySelectorAll(".option") outside the listener, so the options don't exist yet. Move that code inside the listener.
const selected = document.querySelector(".selected");
const optionsContainer = document.querySelector(".options-container");
window.addEventListener('DOMContentLoaded', () => {
createNewOption1();
createNewOption2();
const optionsList = document.querySelectorAll(".option");
optionsList.forEach(o => {
o.addEventListener("click", () => {
selected.innerHTML = o.querySelector("label").innerHTML;
optionsContainer.classList.remove("active");
});
});
});
selected.addEventListener("click", () => {
optionsContainer.classList.toggle("active");
});
const createNewOption1 = () => {
const div1 = document.createElement('div');
const input1 = document.createElement('input');
const label1 = document.createElement('label');
div1.className = 'option';
input1.type = 'radio';
input1.className = 'radio';
input1.name = 'category';
label1.htmlFor = 'Rejuvenating';
label1.innerHTML = 'Rejuvenating Set';
div1.appendChild(input1);
div1.appendChild(label1);
optionsContainer.appendChild(div1);
}
const createNewOption2 = () => {
const div2 = document.createElement('div');
const input2 = document.createElement('input');
const label2 = document.createElement('label');
div2.className = 'option';
input2.type = 'radio';
input2.className = 'radio';
input2.name = 'category';
label2.htmlFor = 'Maintenance';
label2.innerHTML = 'Maintenance Set';
div2.appendChild(input2);
div2.appendChild(label2);
optionsContainer.appendChild(div2);
}
<!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>Database Project</title>
<script src="https://kit.fontawesome.com/d6307e6979.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h2>Sales</h2>
<div class="select-box">
<div class="options-container">
</div>
<div class="selected">
<p>Select Item</p>
</div>
</div>
</div>
<script src="main.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);
}

Why I cannot add new note after editing created one?

I cannot add new Note after editing. How can I exit from the cycle?
This is a part where I create a new note
const createNote = () => {
if (button.className === "button") {
const div = document.createElement("div");
div.setAttribute("class", "note");
div.textContent = input.value;
field.appendChild(div);
const btn = document.createElement("button");
btn.setAttribute("class", "edit");
btn.textContent = "Edit";
div.appendChild(btn);
const del = document.createElement("button");
del.setAttribute("class", "del");
del.textContent = "Delete";
div.appendChild(del);
console.log("Note has been created");
input.value = "";
}
Here is a part where I want to edit created Note but also I want to create a new one (this part is inside function createNote)
const edit = document.querySelectorAll(".edit");
for (let i of edit) {
i.onclick = () => {
input.value = i.previousSibling.nodeValue;
button.innerText = "Edit";
button.classList.add("editable");
/*button.classList.remove("button");*/
if (button.className === "button editable") {
button.onclick = () => {
i.previousSibling.nodeValue = input.value;
input.value = "";
button.classList.remove("editable");
button.classList.add("button");
button.innerText = "Add";
};
}
};
}
};
button.onclick = createNote;
Here is HTML that I am using
<body>
<div class="container">
<div class="insert">
<input type="text" name="Note" id="noteId" placeholder="add note">
<button class="button">Add</button>
</div>
<div class="field">
<div class="note">Test note
<button class="edit">Edit</button>
<button class="del">Delete</button>
</div>
</div>
</div>
<script src="js/index.js"></script>
</body>

Categories

Resources