Target and update a specific element in a table with JavaScript - 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);
}

Related

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

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

Trying to add together multiple inputs in the same input field to get total value

tried cutting the code down as much as possible.
Issue: I'm trying to get the total price of new array objects that are being created from inputs by the user, i tried making a new function that grabs the input, but it changes to the new value in the input field whenever a new item is added. Price also wont change when the user deletes an object from the array.
const itemTotalPrice = document.getElementById("total-price")
const itemContainer = document.getElementById("item-container")
const itemListmore = document.getElementById("item-list-more")
var itemArrayMore = [];
//Functions for user input for item name and price
function additemmore () {
let itemNameInput = document.getElementById("item-name-more").value;
let itemPriceInput = document.getElementById("item-price-more").value;
if(document.getElementById("item-name-more").value.length == 0)
{
alert("Need a name")
return false;
}
if(document.getElementById("item-price-more").value.length == 0)
{
alert("Need a price")
return false;
}
if(document.getElementById("item-price-more").value === 0)
{
alert("Value cannot be 0 or lower")
return false;
}
itemArrayMore.push({
name: itemNameInput,
price: itemPriceInput + "kr",
});
console.log("New Array:", itemArrayMore);
listItemsMore();
priceTotal()
}
function listItemsMore(){
itemListmore.innerHTML ="";
for(let i = 0; i < itemArrayMore.length; i++){
itemListmore.innerHTML += `<li><h1>${itemArrayMore[i].name}</h1>
<h2 id="item-price">${itemArrayMore[i].price}</h2>
<button id="delete-btn" onclick="deleteitemmore(${i})">Delete</button></li>`;
}
}
function deleteitemmore(i) {
let del = "Are you sure you want to delete the selected item?";
if (confirm(del) == true) {
itemArrayMore.splice(i, 1);
listItemsMore();
} else {
alert
}
}
//Function for total price. Goal is to get every input and display it as a total price for the user.
//If possible also remove value if related item is deleted.
function priceTotal() {
var price = document.getElementById("item-price-more").value;
var total = +price;
document.getElementById("total-price").innerHTML = total;
}
<!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>
<h1>Shopping list</h1>
<div id="item-container" class="row">
<div class="column">
<input
type="text"
id="item-name-more"
placeholder="Item name"
/>
<!--for some reason you can add the letter e in the input for price-->
<input
type="number"
id="item-price-more"
placeholder="Write name of item!"
/>
<button onclick="additemmore()">Add</button>
<ul id="item-list-more"></ul>
<ul>Total Price: <span id="total-price">0</span></ul>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
Make total a global variable. Then you can add to it when you add a new item, and subtract from it when you delete an item.
const itemTotalPrice = document.getElementById("total-price")
const itemContainer = document.getElementById("item-container")
const itemListmore = document.getElementById("item-list-more")
var itemArrayMore = [];
var total = 0;
//Functions for user input for item name and price
function additemmore() {
let itemNameInput = document.getElementById("item-name-more").value;
let itemPriceInput = document.getElementById("item-price-more").value;
if (document.getElementById("item-name-more").value.length == 0) {
alert("Need a name")
return false;
}
if (document.getElementById("item-price-more").value.length == 0) {
alert("Need a price")
return false;
}
if (document.getElementById("item-price-more").value === 0) {
alert("Value cannot be 0 or lower")
return false;
}
itemArrayMore.push({
name: itemNameInput,
price: itemPriceInput + "kr",
});
console.log("New Array:", itemArrayMore);
listItemsMore();
priceTotal()
}
function listItemsMore() {
itemListmore.innerHTML = "";
for (let i = 0; i < itemArrayMore.length; i++) {
itemListmore.innerHTML += `<li><h1>${itemArrayMore[i].name}</h1>
<h2 id="item-price">${itemArrayMore[i].price}</h2>
<button id="delete-btn" onclick="deleteitemmore(${i})">Delete</button></li>`;
}
}
function deleteitemmore(i) {
let del = "Are you sure you want to delete the selected item?";
if (confirm(del) == true) {
total -= +itemArrayMore[i].price.replace('kr', '');
document.getElementById("total-price").innerHTML = total;
itemArrayMore.splice(i, 1);
listItemsMore();
} else {
alert
}
}
//Function for total price. Goal is to get every input and display it as a total price for the user.
//If possible also remove value if related item is deleted.
function priceTotal() {
var price = document.getElementById("item-price-more").value;
total += +price;
document.getElementById("total-price").innerHTML = total;
}
<!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>
<h1>Shopping list</h1>
<div id="item-container" class="row">
<div class="column">
<input type="text" id="item-name-more" placeholder="Item name" />
<!--for some reason you can add the letter e in the input for price-->
<input type="number" id="item-price-more" placeholder="Write name of item!" />
<button onclick="additemmore()">Add</button>
<ul id="item-list-more"></ul>
<ul>Total Price: <span id="total-price">0</span></ul>
</div>
</div>
<script src="index.js"></script>
</body>
</html>

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

push created object with class into array

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

How to calculate cashback value using .reduce() method from input value?

I need to make a form where the user can enter the name of the purchase and its value. With each addition, the cashback costs should be calculated automatically (via reduce method). Cashback is 0.5%. All purchases must be contained in the purchases array and have exactly three properties:
id - number
name - string (name of Purchase)
price - number (price of Purchase)
I can't seem to figure out how to use reduce method to calculate cashback value. Besides each cashback value, total cashback should be displayed as well.
let nextId = 1;
const purchases = [];
const cashback = 0.005;
const commentForm = document.querySelector('[data-id="purchase-form"]');
const nameInput = commentForm.querySelector('[data-input="name"]');
const priceInput = commentForm.querySelector('[data-input="price"]');
const button = commentForm.querySelector('[data-input="price"]');
const purchasesList = document.querySelector('[data-id="purchases-list"]');
button.addEventListener('click', () => {
if (nameInput.value != '' && priceInput.value != '') {
purchases.push({
id: nextId++,
name: nameInput.value,
price: priceInput.value,
});
}
createElement(nameInput.value);
nameInput.value = '';
});
function createElement(ci) {
const newPurchase = document.createElement('li');
newPurchase.setAttribute('data-comment-id', nextId - 1);
newPurchase.textContent = `${ci} for sum of ${priceInput.value} $. (cashback- ${cashbackSum})`;
purchasesList.appendChild(newPurchase);
}
function cashbackSum() {
return Number(priceInput, 10) * cashback;
}
<!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></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="purchase-form">
<input data-input="name" />
<input data-input="price" />
<button type="button" data-action="add">Add</button>
</form>
<ul data-id="purchases-list"></ul>
<div>Total cashback is: <span data-id="total cashback"></span></div>
</div>
<script src="./js/app.js"></script>
</body>
</html>
There seemed to be a few bugs in the given snippet:
You are not getting the value of input box on each click so array is not going to contain the new values. [Make them let instead of const and fetch value on each button click event]
CashbackSum function was not being called.
Created a function for totalCashback that uses the reduce method of array to get the total cashback sum.
let nextId = 1;
const purchases = [];
const cashback = 0.005;
const commentForm = document.querySelector('[data-id="purchase-form"]');
let nameInput = commentForm.querySelector('[data-input="name"]');
let priceInput = commentForm.querySelector('[data-input="price"]');
const button = commentForm.querySelector('[data-action="add"]');
const purchasesList = document.querySelector('[data-id="purchases-list"]');
const totalCashback = document.querySelector('[data-id="total cashback"]');
const errorMsg = document.querySelector('[data-id="error"]');
button.addEventListener('click', () => {
nameInput = commentForm.querySelector('[data-input="name"]');
priceInput = commentForm.querySelector('[data-input="price"]');
if (nameInput.value != '' && priceInput.value != '') {
purchases.push({
id: nextId++,
name: nameInput.value,
price: priceInput.value,
});
createElement(nameInput.value);
nameInput.value = '';
errorMsg.textContent = '';
totalCashback.textContent = calculateTotalCashback() + ' $.';
}else{
errorMsg.textContent = 'Please fill both the fields: [name and price]';
}
});
function createElement(ci) {
const newPurchase = document.createElement('li');
newPurchase.setAttribute('data-comment-id', nextId - 1);
newPurchase.textContent = `${ci} for sum of ${priceInput.value} $. (cashback- ${cashbackSum()})`;
purchasesList.appendChild(newPurchase);
}
function cashbackSum() {
return Number(priceInput.value, 10) * cashback;
}
function calculateTotalCashback() {
return purchases.reduce((sum, item) => {
return sum + (parseFloat(item.price, 10) * cashback);
}, 0);
}
<!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></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="purchase-form">
<input data-input="name" />
<input data-input="price" />
<button type="button" data-action="add">Add</button>
<br /><span data-id="error"></span>
</form>
<ul data-id="purchases-list"></ul>
<div>Total cashback is: <span data-id="total cashback"></span></div>
</div>
<script src="./js/app.js"></script>
</body>
</html>

Categories

Resources