I want to use function instead of codes that I wrote in map method and I want to call this function (createItemCart) inside map method but I don't know how to do it.
This is createItemCart function:
const product = event.target.parentElement;
const id = product.id;
const imgProduct = product.querySelector("img").src;
const titleProduct = product.querySelector(".title").innerText;
const priceProduct = Number(product.querySelector(".price").innerText);
const qtyCheck = document.getElementById("item" + id);
let totalPrice = Number(document.querySelector(".total-price").innerText);
document.querySelector(".total-price").innerText = totalPrice + priceProduct;
function createItemCart(imgProduct, titleProduct, priceProduct, totalPrice, id) {
const itemsCart = document.getElementById("items-cart");
document.querySelector(".total-price").innerText = totalPrice + priceProduct;
const item = document.createElement("div");
item.setAttribute("class", "item-cart");
const imgItem = document.createElement("img");
imgItem.src = imgProduct;
const detailItem = document.createElement("div");
const titleItem = document.createElement("div");
titleItem.setAttribute("class", "title-item");
titleItem.innerText = titleProduct;
const divPrice = document.createElement("div");
const priceItem = document.createElement("span");
priceItem.setAttribute("class", "price-item");
priceItem.innerText = priceProduct;
const spanToman = document.createElement("span");
spanToman.innerText = "تومان";
const qtyItem = document.createElement("div");
qtyItem.className = "qty-item";
qtyItem.innerText = "1";
qtyItem.id = "item" + id;
const deleteItem = document.createElement("i");
deleteItem.className = "delete-item";
deleteItem.innerText = "x";
deleteItemCart(deleteItem, totalPrice, priceProduct);
detailItem.appendChild(titleItem);
detailItem.appendChild(divPrice);
detailItem.appendChild(qtyItem);
divPrice.appendChild(priceItem);
divPrice.appendChild(spanToman);
item.appendChild(imgItem);
item.appendChild(detailItem);
item.appendChild(deleteItem);
itemsCart.appendChild(item);
}
This is map method:
items.map((itemCart) => {
const item = document.createElement("div");
item.setAttribute("class", "item-cart");
const imgItem = document.createElement("img");
imgItem.src = itemCart.img;
const detailItem = document.createElement("div");
const titleItem = document.createElement("div");
titleItem.setAttribute("class", "title-item");
titleItem.innerText = itemCart.title;
const divPrice = document.createElement("div");
const priceItem = document.createElement("span");
priceItem.setAttribute("class", "price-item");
priceItem.innerText = itemCart.price;
const spanToman = document.createElement("span");
spanToman.innerText = "تومان";
const qtyItem = document.createElement("div");
qtyItem.className = "qty-item";
qtyItem.innerText = itemCart.qty;
qtyItem.id = "item" + itemCart.id;
totalPrice += itemCart.price * itemCart.qty;
document.querySelector(".total-price").innerText = totalPrice;
sumQty += itemCart.qty;
document.getElementById("number").innerText = sumQty;
const deleteItem = document.createElement("i");
deleteItem.className = "delete-item";
deleteItem.innerText = "x";
deleteItemCart(deleteItem, totalPrice, itemCart.price);
detailItem.appendChild(titleItem);
detailItem.appendChild(divPrice);
detailItem.appendChild(qtyItem);
divPrice.appendChild(priceItem);
divPrice.appendChild(spanToman);
item.appendChild(imgItem);
item.appendChild(detailItem);
item.appendChild(deleteItem);
itemsCart.appendChild(item);
});
For example I don't know how to use itemCart.img in createItemCart Function. Anyone can help?
You don't use itemCart.img in the function, you use it as the argument to the function.
items.forEach(itemCart =>
createItemCart(itemCart.img, itemCart.title, itemCart.price, itemCart.price * itemCart.qty, itemCart.id));
And you should use forEach() rather than map(). map() is used when you want to create an array of the results of the function, but your function doesn't return anything.
Related
I want to select all elements using querySelectorAll with variable "amountClass" but NodeList always is empty
function addingCoin() {
const table = document.querySelector('.list__table');
table.addEventListener('submit', (event) => {
event.preventDefault();
const walletCryptos = document.querySelector('#usersCrypto');
const coinAmount = event.target.inputAmount;
const coinRow = coinAmount.parentElement.parentElement.parentElement;
const coinName = coinRow.querySelector('.name').textContent;
const coinPrice = coinRow.querySelector('.price').textContent.match(/\d+(\.\d+)?/)[0];
const coinValue = coinAmount.value*coinRow.querySelector('.price').textContent.match(/\d+(\.\d+)?/)[0];
let amountClass = coinName;
let existingCoin = document.querySelectorAll(amountClass);
if (existingCoin.length > 0) {
existingCoin[0].innerText = coinAmount.value +
existingCoin[0].value;
} else {
const newTr = document.createElement("tr");
const nameTh = document.createElement("th");
const priceTh = document.createElement("th");
const amountTh = document.createElement("th");
const valueTh = document.createElement("th");
nameTh.innerText = coinName;
if (coinPrice < 0.95) {
priceTh.innerText = parseFloat(coinPrice).toFixed(8);
} else {
priceTh.innerText = parseFloat(coinPrice).toFixed(2);
};
amountTh.innerText = coinAmount.value;
amountTh.className += coinName;
if (coinValue < 0.95) {
valueTh.innerText = parseFloat(coinValue).toFixed(8);
} else {
valueTh.innerText = parseFloat(coinValue).toFixed(2);
};
walletCryptos.appendChild(newTr);
walletCryptos.appendChild(nameTh);
walletCryptos.appendChild(priceTh);
walletCryptos.appendChild(amountTh);
walletCryptos.appendChild(valueTh);
}});
};
I think the problem may be with this part of code:
let existingCoin = document.querySelectorAll(amountClass);
What can i change to make this work properly? Is there any other solution to check does the element with the certain class exist?
You need a . at the beginning to select a class.
Trim the text content in case it has whitespace around the text.
const coinName = coinRow.querySelector('.name').textContent.trim();
let amountClass = '.' + coinName
Finally I have found the solution:
const amountClass = '.' + coinName;
const existingCoin = document.querySelectorAll(amountClass.replace(/ /g,''));
I'm having trouble implementing the logic that will limit me from adding the same items to my shopping list. When the item is the same, I just want to display the quantity with the existing item.
<div class="pizzas">
</div>
<div class="shoppingCart">
<p class="totalPrice">Hungry? order our pizzas</p>
</div>
// js
fetch("https://raw.githubusercontent.com/alexsimkovich/patronage/main/api/data.json")
.then(data => data.json())
.then(data => {
let valueCurrency = 0;
data.forEach(element => {
const shoppingCart = document.querySelector(".shoppingCart");
const pizzas = document.querySelector(".pizzas");
const box = document.createElement("div");
const img = document.createElement("img");
const title = document.createElement("h3");
const ingredients = document.createElement("p");
const price = document.createElement("h4");
const btn = document.createElement("button");
const totalPrice = document.querySelector(".totalPrice");
box.className = "box";
ingredients.className = "ingredients"
btn.className = "btn";
img.src = element.image;
img.className = "img";
title.innerHTML = element.title;
ingredients.innerHTML = element.ingredients;
price.innerHTML = element.price.toFixed(2) + " zł";
btn.innerHTML = "Dodaj do koszyka";
box.appendChild(img);
box.appendChild(title);
box.appendChild(ingredients);
box.appendChild(price);
box.appendChild(btn);
pizzas.appendChild(box);
btn.addEventListener("click", (e) => {
valueCurrency = valueCurrency + element.price;
const pizza = document.createElement("div");
pizza.className = "pizzaList";
const pizzasList = document.createElement("li");
const pizzaPrice = document.createElement("p");
const btnRemove = document.createElement("button");
btnRemove.innerText = "X";
pizzasList.innerText = title.textContent;
pizzaPrice.innerText = price.textContent;
pizza.appendChild(pizzasList);
pizza.appendChild(pizzaPrice);
pizza.appendChild(btnRemove);
totalPrice.innerText = "Całkowita cena: " + valueCurrency.toFixed(2);
if(pizzasList.innerText === pizzasList.innerText)
{
// don't add another item to the list
// just add +1 to existing element
}
else
{
// add an item to the list
shoppingCart.prepend(pizza);
}
btnRemove.addEventListener("click", (e) => {
pizza.remove();
valueCurrency = valueCurrency - element.price;
totalPrice.innerText = "Całkowita cena: " + valueCurrency.toFixed(2);
})
})
});
})
.catch(err => console.log(err));
My problem is exactly in the conditional statement, I don't know exactly how to implement the counting of the same pizzas option.
Thank you in advance for your help.
Since you are using html elements for this, what you can do is to use a data-attribute in your pizza element and increment it each time you need.
Something like:
if(pizzasList === pizzasList)
{
pizza.dataset.total = Number(pizza.dataset.total) + 1;
}
else
{
pizza.dataset.total = 1;
shoppingCart.prepend(pizza);
}
Then just use pizza.dataset.total to retieve the total number of repetitions.
I’m a newbie started js like 2 weeks ago.
I have been making a to-do list.
There are key toDos & finished in localStorage.
I want the value in toDos to go to finished, getting class name “done” if I click the finBtn. Also it should move to the bottom.
At first it works. However, every time the page gets refreshed, the stuff in finished gets duplicated.
This problem’s been bothering me for a week.
Thank you for reading.
const toDoForm = document.querySelector(".js-toDoForm"),
toDoInput = toDoForm.querySelector("input"),
toDoList = document.querySelector(".js-toDoList");
const TODOS_LS = "toDos";
const FINISHED_LS = "finished";
const NOTSTART_CN = "notStart";
const DONE_CN = "done";
let toDos = [];
let toDosDone = [];
function saveToDos(){
localStorage.setItem(TODOS_LS, JSON.stringify(toDos));
}
function updateToDos(){
localStorage.setItem(FINISHED_LS, JSON.stringify(toDosDone));
}
function deleteToDo(event){
const btn = event.target;
const li = btn.parentNode;
toDoList.removeChild(li);
const cleanToDos = toDos.filter(function(toDo){
return toDo.id !== parseInt(li.id);
});
toDos = cleanToDos;
saveToDos();
}
function finish(event){
const btn = event.target;
const li = btn.parentNode;
const oldToDos = localStorage.getItem(TODOS_LS);
const parsedOldToDos = JSON.parse(oldToDos);
const btnNum = parseInt(li.id) - 1;
const finishedStuff = parsedOldToDos.splice(btnNum, 1);
finishedStuff[0].class = DONE_CN;
li.classList.add(DONE_CN);
toDos = parsedOldToDos;
toDosDone = finishedStuff;
saveToDos();
updateToDos();
}
function makeToDos(text){
const li = document.createElement("li");
const span = document.createElement("span");
const delBtn = document.createElement("button");
const finBtn = document.createElement("button");
const newId = toDos.length + 1;
delBtn.innerText="❌";
delBtn.classList.add("delBtn");
delBtn.addEventListener("click", deleteToDo);
finBtn.classList.add("finBtn");
finBtn.innerText = "✔";
finBtn.addEventListener("click", finish);
span.innerText = text;
li.id = newId;
li.appendChild(span);
li.appendChild(delBtn);
li.appendChild(finBtn);
toDoList.appendChild(li);
const toDoObj = {
text: text,
id: newId,
class:""
};
toDos.push(toDoObj);
saveToDos();
}
function handleSubmit(event){
event.preventDefault();
const currentValue = toDoInput.value;
makeToDos(currentValue);
toDoInput.value = "";
}
function loadToDos(){
const loadedToDos = localStorage.getItem(TODOS_LS);
const loadedFinToDos = localStorage.getItem(FINISHED_LS);
if(loadedToDos !== null || loadedFinToDos !== null){
const parsedToDos = JSON.parse(loadedToDos);
const parsedFinToDos = JSON.parse(loadedFinToDos);
parsedToDos.forEach(function(toDo){
makeToDos(toDo.text);
});
parsedFinToDos.forEach(function(done){
makeToDos(done.text);
});
} //else
} //ends of loadToDos
function init(){
loadToDos();
toDoForm.addEventListener("submit", handleSubmit);
}
init();
Your localStorage is not cleaning up on page refresh, you should do localStorage.clear(); Each time page load using
I'm making a browser game but I've run into a issue I cant fix no matter how hard I try.
Click the green square increases the counter
and console shows variable being saved to localStorage
but upon returning on the website it returns to 0
Below is my entire JS file. Only part that matters is at the bottom and you can go see for yourself at https://sleepyshepherd.com
//Saved Variables
let ashCount = 0;
let firetruck = 0;
//Initialize Game
window.onload = function() {
const realmTab = document.createElement("div");
const settingsTab = document.createElement("div");
const shopTab = document.createElement("div");
const statsTab = document.createElement("div");
const upgradesTab = document.createElement("div");
const burningBtn = document.createElement("div");
const enslavedTab = document.createElement("div");
const e1 = document.createElement("div");
realmTab.id = "realm";
upgradesTab.id = "upgrades";
settingsTab.id = "settings";
shopTab.id = "shop";
statsTab.id = "stats";
enslavedTab.id = "enslaved";
burningBtn.id = "burning";
e1.id = "e1";
const t1 = document.createTextNode("Realm");
realmTab.appendChild(t1);
const t2 = document.createTextNode("Upgrades");
upgradesTab.appendChild(t2);
const t3 = document.createTextNode("Shop");
shopTab.appendChild(t3);
const t4 = document.createTextNode("Stats");
statsTab.appendChild(t4);
const t5 = document.createTextNode("Settings");
settingsTab.appendChild(t5);
document.getElementById("menu").appendChild(realmTab);
document.getElementById("menu").appendChild(upgradesTab);
document.getElementById("menu").appendChild(shopTab);
document.getElementById("menu").appendChild(statsTab);
document.getElementById("menu").appendChild(settingsTab);
document.getElementById("destroy").appendChild(burningBtn);
document.getElementById("destroy").appendChild(enslavedTab);
document.getElementById("enslaved").appendChild(e1);
//Menu Buttons
const viewport1 = document.querySelector(".viewport");
//Realm View Select
document.querySelector("#realm").addEventListener("click", function() {
viewport1.id = "realmView";
});
//Upgrades View Select
document.querySelector("#upgrades").addEventListener("click", function() {
viewport1.id = "upgradeView";
});
//shop View Select
document.querySelector("#shop").addEventListener("click", function() {
viewport1.id = "shopView";
});
//stats View Select
document.querySelector("#stats").addEventListener("click", function() {
viewport1.id = "statsView";
});
//settings View Select
document.querySelector("#settings").addEventListener("click", function() {
viewport1.id = "settingsView";
});
// Destroy
function increaseAsh() {
ashCount += 1;
}
document.querySelector("#destroy").addEventListener("click", increaseAsh);
//Resources
const r1 = document.createElement("div");
r1.id = "r1";
document.querySelector("#resources").appendChild(r1);
const t6 = document.createElement("p");
r1.appendChild(t6);
window.setInterval(function() {
t6.textContent = ashCount;
}, 16);
//load game
let sg = JSON.parse(localStorage.getItem("save"));
sg.ashCount = ashCount;
}
// Save Game Interval
window.setInterval(function() {
let save = {
ashCount: ashCount,
firetruck: firetruck
}
localStorage.setItem("save", JSON.stringify(save));
}, 10000);
you wrote sg.ashCount = ashCount; when you want ashCount = sg.ashCount;
add a console.log(sg);
I'm solving this problem, I want to add and remove items to the HTML table using javascript. So far I've got this, but I don't really know how to make the removing part possible. Could you give me a hand please?
let inputJmeno = document.querySelector('#inputJmeno');
let inputPrijmeni = document.querySelector('#inputPrijmeni');
let inputVek = document.querySelector('#inputVek');
let buttonAdd = document.querySelector('#add');
let table = document.querySelector('table');
let tbody = document.querySelector('tbody');
let tr = document.querySelector('tr');
let jmeno = null;
let prijmeni = null;
let vek = null;
let pocetOsob = 0;
buttonAdd.addEventListener('click', add);
function add() {
jmeno = inputJmeno.value;
prijmeni = inputPrijmeni.value;
vek = inputVek.value;
let newRow = document.createElement('tr');
let newJmeno = document.createElement('td');
let newPrijmeni = document.createElement('td');
let newVek = document.createElement('td');
let krizek = document.createElement('span');
krizek.id = "krizek" + pocetOsob;
krizek.className = "krizClass";
newRow.id = "row" + pocetOsob;
newJmeno.innerHTML = jmeno;
newPrijmeni.innerHTML = prijmeni;
newVek.innerHTML = vek;
krizek.innerHTML = 'x';
tbody.appendChild(newRow);
newRow.appendChild(newJmeno);
newRow.appendChild(newPrijmeni);
newRow.appendChild(newVek);
newRow.appendChild(krizek);
load(pocetOsob);
pocetOsob++;
}
function load(p) {
let krz = document.querySelector('#krizek'+p);
console.log(p);
}
try
newRow.removeChild(krizek);