add to cart button is not responding - javascript

my add to cart button is not responding. I have applied javascript on my add to cart button, In the cart button, I have assigned attribute i.e data-product the value that is {{product.id}}.
var updateBtns = document.getElementsByClassName('update-cart')
for (var i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function() {
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'action:', action)
})
}
<div class="card-body">
<h5 class="card-title fw-bold text-uppercase">{{product.name}}</h5>
<p class="card-text">
<h4 style="font-size: 1rem; padding: 0.3rem;
opacity: 0.8;">$ {{product.price}} </h4>
</p>
<button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">ADD TO CART</button>
</div>
</div>
The console is not showing anything even though I click on Add to Cart button several times

Instead of getElementsByClassName use querySelectorAll beacuse as #tacoshy stated getElementsByClassName returns an object of HTML Collection not an array. Also length would return the amount of elements within an array but not an object.
const updateBtns = document.querySelectorAll('.update-cart')
updateBtns.forEach((updateBtn) => {
updateBtn.addEventListener('click', (event) => {
var productId = updateBtn.dataset.product
var action = updateBtn.dataset.action
console.log('productId:', productId, 'action:', action)
})
})

Related

How to delete firebase child data in Javascript?

The script is like this to show the data from firebase database:
const onChildAdd = (snap) => { $('#contacts').append(contactHtmlFromObject(snap.key, snap.val()));}
//prepare contact object's HTML
const contactHtmlFromObject = (key, contact) => `
<div class="card contact" style="width: 100%;" id="${key}">
<div class="card-body">
<button class="arrival btn btn-danger btn-xs" onclick="delete_user()">X</button>
<h5 class="card-title">User: ${contact.a2}</h5>
<h6 class="card-subtitle mb-2 text-muted">User1: ${contact.a3}</h6>
<p class="card-text" title="${contact.a1}">
Expiry:${contact.a1} - Vip:${contact.a4} - Status:${contact.a5}
</p>
<input type="text" class="form-control" id="kea" value="${contact.a7}">
</div>
</div>`;
const spanText = (textStr, textClasses) => { const classNames = textClasses.map(c => `text-${c}`).join(' ');
return `<span class="${classNames}">${textStr}</span>`;}
I also have a function:
function delete_user() { firebase.database().ref().child("contact/" + auth.uid + "/" + $('#kea').val()).remove();
alert('The user is deleted successfully!'); }
I use input text to show my child key -Kvhovcjoggiobhuoy something like this or whatever.
I'm trying to delete child key with function delete_user() when click the button.
Any way to correct it, or any other way to delete it?

Why is my .empty() not emptying the parent element?

I cannot get the jQuery empty method to work on my appended HTML elements.
It's quite a simple problem seemingly, but it has me beat.
I've tried moving the empty method around in the code but I still cannot get it to empty.
Edit: It will not let me edit this unless there is more text so here is some more text.
My jQuery/JavaScript:
// Declares blank arrays
let monthHolidayName = [];
let monthHolidayDescription = [];
let monthHolidayDay = [];
let monthHolidayMonth = [];
let monthHolidayIsoDate = [];
// On change pushes the arrays with the current months data
$('#monthSelect').change(function(){
var selectedMonth = $('#monthSelect').val();
var numSelectedMonth = parseInt(selectedMonth) + 1;
for(i = 0; i < result['data']['holidays'].length; i++){
var holidayMonth = result['data']['holidays'][i]['date']['datetime']['month'];
if(holidayMonth === numSelectedMonth){
// console.log((result['data']['holidays'][i]));
monthHolidayName.push(result['data']['holidays'][i]['name']);
monthHolidayDescription.push(result['data']['holidays'][i]['description']);
monthHolidayDay.push(result['data']['holidays'][i]['date']['datetime']['day']);
monthHolidayMonth.push(result['data']['holidays'][i]['date']['datetime']['month']);
monthHolidayIsoDate.push(result['data']['holidays'][i]['date']['iso']);
}
}
// Empties the #holidays element <--------------------
$("#holidays").empty();
// Appends the data to the modal
for(i = 0; i < monthHolidayName.length; i++){
var holidayName = monthHolidayName[i];
var holidayDescription = monthHolidayDescription[i];
var holidayDay = monthHolidayDay[i];
var holidayDayMonth = monthHolidayMonth[i];
var holidayIsoDate = monthHolidayIsoDate[i];
var dateParsed = Date.parse(`${holidayDay} ${holidayDayMonth}`).toString("MMMM dS");
// Appends elements to #holidays with the data
$("#holidays").append(`<div class="list-group-item list-group-item-action"><div style="text-decoration: underline; text-align: center;">${holidayName}</div><div style="text-align: center">${holidayDescription}</div><small class="text-muted">${holidayIsoDate}</small></div>`);
}
});
My HTML code:
<!-- Calendar Modal -->
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="modal fade " id="calendar-modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 id="modalTitle">Holidays</h1>
<button type="button" class="close btn btn-secondary" data-bs-dismiss="modal" >×</button>
</div>
<!-- This is the body section of our modal overlay -->
<div class="modal-body" id="modalBody">
<div class="btn-group dropright">
<select class="form-select form-select-sm mb-3" id="monthSelect">
</select>
</div>
<div class="list-group">
<button type="button" class="list-group-item list-group-item-action active" id="holidayTitle">
Holidays in <span id="currentMonth"></span>
</button>
<span id="holidays">
</span>
</div>
</div>
<!-- This is the footer section of our modal overlay -->
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" >Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
It seems that you want to both append new data to your existing data while also deleting the old data. Your code is constantly referencing append, which implies that you want to keep the previous data, but your question asks about how to clear the holidays div, and then add the new holiday.
Answering your question, we don't need an array if we're always deleting the previous holiday information, instead we can use a JavaScript Object to hold the information. The other portion that you'll notice I changed is I took out the for loop you had. Since we have a single holiday, we don't need to iterate through an array. The following code should show how to work with a single holiday in an Object. Note that I did not change the HTML
// Declare an object with our empty parameters:
let holiday = {
name: "",
description: "",
day: "",
month: "",
isoDate: ""
};
// On change pushes the arrays with the current months data
$('#monthSelect').change(function(){
var selectedMonth = $('#monthSelect').val();
var numSelectedMonth = parseInt(selectedMonth) + 1;
for(i = 0; i < result['data']['holidays'].length; i++){
var holidayMonth = result['data']['holidays'][i]['date']['datetime']['month'];
if(holidayMonth === numSelectedMonth){
// console.log((result['data']['holidays'][i]));
// Using object setter notation to change each key:
holiday.name = result['data']['holidays'][i]['name'];
holiday.description = result['data']['holidays'][i]['description'];
holiday.day = result['data']['holidays'][i]['date']['datetime']['day'];
holiday.month = result['data']['holidays'][i]['date']['datetime']['month'];
holiday.isoDate = result['data']['holidays'][i]['date']['iso'];
}
}
// Empties the #holidays element <--------------------
$("#holidays").empty();
var dateParsed = Date.parse(`${holiday.day} ${holiday.month}`).toString("MMMM dS");
// Appends elements to #holidays with the data
$("#holidays").append(`<div class="list-group-item list-group-item-action"><div style="text-decoration: underline; text-align: center;">${holiday.name}</div><div style="text-align: center">${holiday.description}</div><small class="text-muted">${holiday.isoDate}</small></div>`);
});
You can manage this
$("#yourDiv").html(""); // jQuery

To Do list with check button

I want to make my own To Do list using JavaScript and localStorage. After writing the input and pressing the send button, the item will be added and display on the screen. A check button will appear next to the item. After pressing the check button, I want the class to be added. I want add css (opacity, line...). But when I press a check button, the console shows this error: Uncaught TypeError: Cannot read properties of undefined (reading 'add')
at check (app.js:23)
at HTMLElement.onclick (index.html:30)
HTML code:
<body>
<div class="main">
<input id="item" type="text">
<i id="addItem" class="fas fa-plus"></i><br> <br>
</div>
<div class="items">
<div id="addedItems"></div>
</div>
<i onclick='deleteAll()' class="fas fa-trash"></i>
</body>
JS code:
const item = document.getElementById("item");
const add = document.getElementById("addItem");
const addedItems = document.getElementById("addedItems");
add.onclick = function() {
const itemValue = item.value;
const itemValue2 = ' ';
if (itemValue && itemValue2) {
localStorage.setItem(itemValue, itemValue2);
location.reload();
}
};
for (let a = 0; a < localStorage.length; a++) {
const itemValue = localStorage.key(a);
addedItems.innerHTML += `<div class= 'text'> <div>${itemValue}</div> <div>
<i onclick='check("${itemValue}")' class="fas fa-check"></i><i
onclick='deleteItem("${itemValue}")' class="fas fa-trash-alt"></i>
</div></div> <br>`;
}
function check(itemValue) {
itemValue.classList.add("mystyle");
}
function deleteItem(itemValue) {
localStorage.removeItem(itemValue);
location.reload();
}
function deleteAll() {
localStorage.clear();
location.reload();
}
You can try this answer:
<script>
const item = document.getElementById("item");
const add = document.getElementById("addItem");
const addedItems = document.getElementById("addedItems");
add.onclick = function() {
const itemValue = item.value;
const itemValue2 = ' ';
if (itemValue && itemValue2) {
localStorage.setItem(itemValue, itemValue2);
location.reload();
}
};
for (let a = 0; a < localStorage.length; a++) {
const itemValue = localStorage.key(a);
addedItems.innerHTML += `<div class= 'text'> <div>${itemValue}</div> <div>
<i onclick='check("${itemValue}", ${a})' class="fas fa-check" id="${a}"></i><i
onclick='deleteItem("${itemValue}")' class="fas fa-trash-alt"></i>
</div></div> <br>`;
}
function check(itemValue, id) {
const elem = document.getElementById(id);
elem.classList.add("mystyle");
}
function deleteItem(itemValue) {
localStorage.removeItem(itemValue);
location.reload();
}
function deleteAll() {
localStorage.clear();
location.reload();
}
</script>
<div class="main">
<input id="item" type="text">
<i id="addItem" class="fas fa-plus"></i><br> <br>
</div>
<div class="items">
<div id="addedItems"></div>
</div>
<i onclick='deleteAll()' class="fas fa-trash"></i>
Only changes I made is pass id of element for checkbox click along with itemValue element. Value you are passing checkbox value not document element. If you console you will get to know itemValue is just string not DOM element.
Here is fiddle : https://jsfiddle.net/aviboy2006/ortqu1ps/

how to remove a list item in a list which uses cloud firestore and javascript [duplicate]

This question already has answers here:
Remove elements onclick (including the remove button itself) with jQuery
(3 answers)
Closed 2 years ago.
function renderlist(doc) {
const listmon = document.querySelector("#item-list");
db.collection("cafes")
.get()
.then((snapshot) => {
list(snapshot.docs);
});
const list = (data) => {
let html = "";
data.forEach((doc) => {
const guide = doc.data();
auth.onAuthStateChanged((user) => {
if (user) {
const li = `<li class=${user.uid}>
<div class="card">
<a
href="#"
class="btn btn-fix text-left"
data-toggle="modal"
data-target="#exampleModal"
>
<div class="card-block">
<h4 class="card-title text-dark">${guide.name}</h4>
<p class="card-text text-dark">
${guide.city}
</p>
<a href="#" class="btn btn-primary" id="delete" onclick="arun (){
console.log("clicked");
};">delete</a>
<p class="card-text">
<small class="text-muted">Last updated 3 mins ago</small>
</p>
</div>
</a>
</div>
</li>
<div
class="modal "
id="exampleModal"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button
type="button"
class="close"
data-dismiss="modal"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div
class="modal-body"
data-toggle="modal"
data-target="#exampleModal"
>
${guide.name}
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-dismiss="modal"
>
Close
</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>`;
html += li;
listmon.innerHTML = html;
} else {
console.log("logged out");
}
});
});
};
}
i created it using javascript and i want to remove it by clicking a button also i have used user uid as the lists id, when ever i click the button it should remove the list and from cloud firestore it would also be great if somebody could tell me how to only show users data to that particular user,sorry for the language and thanks in advance
I created this simple example to list users with the methods add, delete and show info.
These Firestore/firebase documents [Queries | Modify a document | resource parts ] can be helpful for you to understand better the methods that I used, please feel free to modify this code.
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.18.0/firebase-firestore.js"></script>
</head>
<body>
<h1>Users</h1>
<div class="content">
<form id="add-user-form">
<input type="text" name="name" placeholder="user Name">
<input type="text" name="location" placeholder="user Location">
<button type="submit">Submit</button>
</form>
<ul id="user-list">
<div id="loader">Loading...</div>
</ul>
</div>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const userList = document.querySelector("#user-list");
const form = document.querySelector("#add-user-form");
//add listener to form, to create new users and avoid default form action
form.addEventListener("submit", e => {
e.preventDefault();
db.collection("users").add({
name: form.name.value,
location: form.location.value
});
form.name.value = "";
form.location.value = "";
});
//Create the users list with the firestore data
function renderuser(doc) {
//creating html elements
let li = document.createElement("li");
let name = document.createElement("span");
let del = document.createElement("button");
let info = document.createElement("button")
//add docuemnt ID to the list element
li.setAttribute("data-id", doc.id);
name.textContent = doc.data().name ;
location.textContent = doc.data().location;
//labels of the buttons
// i= info and x= delete user
info.textContent="i"
del.textContent = "X";
// add onclick action to the buttons
del.onclick=function(){deleteUser(doc.id);}
info.onclick=function(){getData(doc.id);}
// add elements to the list element
li.appendChild(name);
li.appendChild(del);
li.appendChild(info);
// add list element to the list
userList.appendChild(li);
}
function deleteUser(id){
db.collection("users")
.doc(id)
.delete();
}
// Getting Data
function getData(id) {
// __name__ is the reference for the id in firestore
db.collection("users").where("__name__", "==", id).get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc)
//this alert simulate the modal
alert("name: "+doc.data().name+"\nlocation: "+doc.data().location)
});
})
}
//this is not used but this is the method to update the data of a docuemnt(User)
function updateData(id,name,location){
db.collection("users").doc(id).set({
name: name,
location: location
}).then(function() {
alert("Document successfully written!");
})
.catch(function(error) {
alert("Error writing document: ", error);
});
}
// Realtime listener
// this function keep updated the list
function getRealtimeData() {
document.querySelector("#loader").style.display = "block";
//query all users
db.collection("users")
.orderBy("name")
.onSnapshot(snapshot => {
document.querySelector("#loader").style.display = "none";
let changes = snapshot.docChanges();
changes.forEach(change => {
if (change.type === "added") {
//add new users to the list on frist load this create the list of existent users
renderuser(change.doc);
} else if (change.type === "removed") {
//if an user is deleted this will remove the element of the list
let li = userList.querySelector(`[data-id=${change.doc.id}]`);
userList.removeChild(li);
}
});
});
}
//first run
getRealtimeData();
</script>
</body>
</html>

How to add a specific item innerText when click

I'm trying to build a simple shopping cart. I want to add the whole item to the cart when clicking the add button. The item looks like this (there are 6 with different name and prices
For now I'm working on adding to the cart just the name (I will use the same process for the price), but when I click the add button it adds the name of the last item and not the one I'm clicking. How do I fix this?
const cart = document.querySelector(".cart");
const productName = document.querySelectorAll(".product-name");
const productPrice = document.querySelector(".product-price");
const addBtn = document.querySelectorAll(".add");
addBtn.forEach(button => {
button.addEventListener("click", addToCart);
})
//Add to cart
function addToCart(e) {
e.preventDefault();
//Create DIV
const item = document.createElement("div");
item.classList.add("item");
//Add name
const name = document.createElement("h2");
name.classList.add("product-name");
productName.forEach(productN => {
name.innerText = productN.innerText;
})
item.appendChild(name);
cart.appendChild(item);
}
<div class="product">
<h2 class="product-name">Beer</h2>
<h3 class="product-price">$4</h3>
<button class="add">Add to cart</button>
</div>
<div class="product">
<h2 class="product-name">Burger</h2>
<h3 class="product-price">$12</h3>
<button class="add">Add to cart</button>
</div>
<section class="section">
<h2 class="text-center">Cart</h2>
<div class="cart"></div>
</section>
You likely want this
const cart = document.getElementById("cart");
const productName = document.querySelectorAll(".product-name");
const productPrice = document.querySelector(".product-price");
const addBtn = document.querySelectorAll(".add");
addBtn.forEach(button => {
button.addEventListener("click", addToCart);
})
//Add to cart
function addToCart(e) {
e.preventDefault();
//Create DIV
const item = document.createElement("div");
item.classList.add("item");
//Add name
const name = document.createElement("h2");
name.classList.add("product-name");
name.innerText = e.target.parentNode.querySelector(".product-name").innerText;
item.appendChild(name);
cart.appendChild(item);
}
<div class="product">
<h2 class="product-name">Beer</h2>
<h3 class="product-price">$4</h3>
<button class="add">Add to cart</button>
</div>
<div id="cart"></div>
Delegate the click from the products
const cart = document.getElementById("cart");
const products = document.getElementById("products");
const productName = document.querySelectorAll(".product-name");
const productPrice = document.querySelector(".product-price");
products.addEventListener("click", addToCart);
//Add to cart
function addToCart(e) {
e.preventDefault();
const tgt = e.target;
if (!tgt.classList.contains("add")) return; // not a button
const parent = tgt.parentNode;
//Create DIV
const item = document.createElement("div");
item.classList.add("item");
//Add name
const name = document.createElement("h2");
name.classList.add("product-name");
name.innerText = parent.querySelector(".product-name").innerText;
item.appendChild(name);
cart.appendChild(item);
}
<div id="products">
<div class=" product ">
<h2 class="product-name ">Beer</h2>
<h3 class="product-price ">$4</h3>
<button class="add ">Add to cart</button>
</div>
<div class="product ">
<h2 class="product-name ">Wine</h2>
<h3 class="product-price ">$4</h3>
<button class="add ">Add to cart</button>
</div>
</div>
<div id="cart"></div>

Categories

Resources