I'm trying to find out how to add a product to my cart once the 'add to cart' button is clicked, but since my cart and products are on separate html pages the console giving me this error
here is the JS for the product pages
var addToCartButtons = document.getElementsByClassName('cta')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
// Add Item to cart
function addToCartClicked(event) {
var button = event.target
var showcaseItem = button.parentElement.parentElement
var title = showcaseItem.getElementsByClassName('pp-title')[0].innerText
var price = showcaseItem.getElementsByClassName('pp-price')[0].innerText
var imgSrc = showcaseItem.getElementsByClassName('pp-img')[0].src
console.log(title, price, imgSrc)
addItemToCart(title, price, imgSrc)
}
function addItemToCart(title, price, imgSrc) {
var cartRow = document.createElement('div')
cartRow.innerText = title + price
var cartItems = document.getElementsByClassName('all-cart-items')[0]
cartItems.append(cartRow)
}
I believe it's because the element with the class 'all-cart-items' is on the cart markup and not the product page but I don't how to target that page with code. Would I need to use php?
I can also attach the html markups for both pages if necessary!
I have make a sample code using localstorage for adding item to car
var addToCartButtons = document.getElementsByClassName('cta')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
// Add Item to cart
function addToCartClicked(event) {
var button = event.target
var showcaseItem = button.parentElement.parentElement
var title = showcaseItem.getElementsByClassName('pp-title')[0].innerText
var price = showcaseItem.getElementsByClassName('pp-price')[0].innerText
var imgSrc = showcaseItem.getElementsByClassName('pp-img')[0].src
console.log(title, price, imgSrc)
addItemToCart(title, price, imgSrc)
}
function addItemToCart(title, price, imgSrc) {
var cartRow = document.createElement('div')
cartRow.innerText = title + price
var cartItems = document.getElementsByClassName('all-cart-items')[0]
cartItems.append(cartRow);
var cart = JSON.parse(localStorage.getItem("cartItemsr"));
if(cart != null && cart.length > 0){
cart({title: title, price: price, img: imgSrc});
}else{
cart = [{title: title, price: price, img: imgSrc}];
}
localStorage.setItem("cartItemsr", JSON.stringify((cart));
}
To retire the items in another page
var cart = JSON.parse(localStorage.getItem("cartItemsr"));
if(cart != null && cart.length > 0){
for (var i = 0; i < cart.length; i++) {
console.log("row", cart[I].title, cart[I].price, cart[I].img)
}
}
Frankly, this demands for some state management libraries or server side rendering languages like PHP. Yes, you would definitely need to save cart info, in the server, so I am sure you would have thought of that. However, to answer to the point,
you can store all the products in localStorage by doing JSON.stringify and in the cart page listen to the storage event and then do JSON.parse and save the info.
Do the below in product page
const list = JSON.parse(localStorage.getItem('productList'));
list.push(newItem)
localStorage.setItem('productList',JSON.stringify(list));
Do the below in cart page
window.addEventListener('storage', () => {
// When local storage changes, dump the list to
// the console.
console.log(JSON.parse(window.localStorage.getItem('productList')));
});
Related
I'm building a library app from The Odin Project, and this error occurs when I try to change read status for Not Read read using a click event.
the error occurs on line 88, reading status value. How can I fix that?
thank you.
console.log(
"What is the toggle initial value?...",
myLibrary[parseInt(retrieveBookToToggle)].status
);
let myLibrary = [];
const btnAdd = document.querySelector("btn-add");
//Object Constructor
class Book {
constructor(title, author, pages, status) {
this.title = title;
this.author = author;
this.pages = pages;
this.status = status;
}
//Add a new book to array
function addBookToLibrary(title, author, pages, status) {
let book = new Book(title, author, pages, status);
myLibrary.push(book);
displayBooksOnPage()
}
//Display array to card
function displayBooksOnPage() {
const books = document.querySelector(".books-container");
//remove displayed cards before loop array
const removeDivs = document.querySelectorAll(".card");
console.log("Show me the node count of the current card divs........", removeDivs);
for (let i = 0; i < removeDivs.length; i++) {
removeDivs[i].remove();
}
//Loop Library array and display to the cards
let index = 0;
myLibrary.forEach(myLibrarys => {
const card = document.createElement("div");
card.classList.add("card");
books.appendChild(card);
//remove book button
const removeBookButton = document.createElement("button");
removeBookButton.classList.add("remove-book-button");
removeBookButton.textContent = "Remove Book";
console.log("show me my currentnarray objects inside of foreach........", myLibrary);
//link data attribute of the remove button to the array and card
removeBookButton.dataset.linkedArray = index;
index++;
console.log("show me dataset link back to the array...", removeBookButton.dataset.linkedArray);
card.appendChild(removeBookButton);
//start event listener/remove array item from array and card from parent div via data link
removeBookButton.addEventListener("click", removeBookFromLibrary);
function removeBookFromLibrary() {
let retrieveBookToRemove = removeBookButton.dataset.linkedArray;
console.log("attempting to remove array item via data attribute...", parseInt(retrieveBookToRemove));
myLibrary.splice(parseInt(retrieveBookToRemove), 1);
card.remove();
displayBooksOnPage;
}
const readStatusButton = document.createElement("button");
readStatusButton.classList.add("read-status-button");
readStatusButton.textContent = "Change Status";
readStatusButton.dataset.linkedArray = index;
console.log("show dataset link back to the array for read status button", readStatusButton.dataset.linkedArray);
card.appendChild(readStatusButton);
readStatusButton.addEventListener("click", toggleReadStatus);
function toggleReadStatus() {
let retrieveBookToToggle = readStatusButton.dataset.linkedArray;
Book.prototype = Object.create(Book.prototype);
const toggleBook = new Book();
console.log("what's the toggle initial value? ", myLibrary[parseInt(retrieveBookToToggle)].status);
if (myLibrary[parseInt(retrieveBookToToggle)].status == "Read") {
toggleBook.status = "Not Read";
myLibrary[parseInt(retrieveBookToToggle)].status = toggleBook.status;
} else if (myLibrary[parseInt(retrieveBookToToggle)].status == "Not Read") {
toggleBook.status = "Read";
myLibrary[parseInt(retrieveBookToToggle)].status = toggleBook.status;
}
displayBooksOnPage();
}
for (let key in myLibrarys) {
const para = document.createElement("p");
para.textContent = (`${myLibrarys[key]}`);
card.appendChild(para);
}
})
}
const addBookButton = document.querySelector(".btn-add");
addBookButton.addEventListener("click", displayTheForm);
function displayTheForm() {
document.getElementById("books-form").style.display = "";
}
const submitButton = document.querySelector(".btn-add");
submitButton.addEventListener("click", intakeFormData);
function intakeFormData() {
let Title = document.getElementById("title").value;
let Author = document.getElementById("author").value;
let Pages = document.getElementById("pages").value;
let Status = document.getElementById("status").value;
if ((Title == "") || (Author == "") || (Pages == "") || (Status == "")) {
return;
}
addBookToLibrary(Title, Author, Pages, Status);
document.getElementById("add-book").reset();
}
const clearButton = document.getElementById("btn-reset");
clearButton.addEventListener("click", clearForm());
function clearForm() {
document.getElementById("add-book").reset();
}
New to JS and trying to create a simple shopping cart using only vanilla JS. I have an item with details and an image that populates on a shopping cart page. I need to have a delete button that allows items to be removed individually from the shopping cart page. Below is the snippet of code I'm having trouble with:
function deleteProduct(i) {
alert('i : ' + i)
productArr2.splice(i,1)
console.log(productArr2)}
And below is the full JS code in case it would be helpful for debugging. Any help is appreciated!:
//Global Variables
var quantity = "";
var glazes = "";
var img = "";
var addItem = "";
//Changes price when quantity is selected
function priceCounter(){
var price = document.getElementById("price-details");
price.innerHTML = document.getElementById("quantity").value;
}
function setImage(select){
var image = document.getElementsByName("image-swap")[0];
image.src = select.options[select.selectedIndex].value;
}
function items(title, quantity, glaze, price, img){
this.title = title;
this.quantity = quantity;
this.glaze = glaze;
this.price = price;
this.img = img;
}
//Add to Cart Functionality
function addToCart() {
var quantityCount = document.getElementById("quantityCount");
quantityCount.innerText = document.getElementById("quantity").value;
document.getElementById("quantityCount").style.visibility = "visible";
title = document.getElementsByClassName("productTitle");
quantity = document.getElementById("quantity").value;
glazing = document.getElementById("glazing").value;
price = document.getElementById("quantity").value;
img = "images/blackberry-bag.png"
addItem = new items(title, quantity, glazing, price, img);
window.localStorage.setItem(localStorageCount, JSON.stringify(addItem));
// localStorageCount += 1;
}
//creates array to hold bag items
var productArr = []
var productArr2 = []
class Product {
constructor(quantity, glaze) {
this.quantity = quantity
this.glaze = glaze
}
}
function addToCart() {
var quantity = document.getElementById('quantity').value
var glaze = document.getElementById('glaze').value
var bun = new Product(quantity, glaze)
productArr.push(bun)
updateCartNumber(productArr.length)
}
function goToCheckoutPage() {
alert("taking you to your cart")
localStorage.setItem('order', JSON.stringify(productArr))
window.location.replace("cart.html")
}
function checkoutPageLoaded() {
var loadedProductArr = localStorage.getItem('order')
var productArr2 = JSON.parse(loadedProductArr)
console.log(productArr2)
var cart = document.getElementById("cart")
for(var i = 0; i < productArr2.length; i++) {
var cinbun = productArr2[i]
var cinbunGlaze = cinbun.glaze
var cinbunQuantity = cinbun.quantity
cart.innerHTML += "<div class='cart-items'> Flavor: Pumpkin Spice Glaze: <img src="+ cinbunGlaze +"> Price: "+ cinbunQuantity +"</div>"
cart.innerHTML += "<span onclick= 'deleteProduct(" + i + ")'> Delete </span>"
}
}
function saveEdits() {
localStorage.setItem('order', JSON.stringify(productArr2))
}
function deleteProduct(i) {
alert('i : ' + i)
productArr2.splice(i,1)
console.log(productArr2)
}
function updateCartNumber(num) {
var cartCount = document.getElementById('quantityCount')
cartCount.innerHTML = num
}
I have a web app with one drop down list and 2 buttons. The drop down list get values from a sheet. The buttons write back in the sheet. The script I have works fine with that:
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(opt)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<opt.length;i++)
{
select.options[i] = new Option(opt[i],opt[i]);
}
}
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
}
}
document.getElementById("but1").addEventListener("click",listS);
function yourCallBack(response) {
}
</script>
In Java script:
function getSelectOptions()
{
var ss=SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh=ss.getSheetByName('Database');
var rg=sh.getRange(2,1,sh.getLastRow()-1,8);
var vA=rg.getValues();
var useremail = Session.getActiveUser().getEmail();
var opt=[];
for(var i=0;i<vA.length;i++)
{
if(vA[i][1] == "Pending Approval"){
if(vA[i][7]+"#xxx.com" == useremail || vA[i][7]+"#xxx.com" == useremail) {
opt.push(vA[i][3]+" REQ ID: "+vA[i][0]);
}
}
};
if (opt.length == 0) {opt.push("You do not have pending requests")};
return opt;
}
function doGet() {
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
}
function yourServerSideFunc(body) {
var value = body["value"];
var ss = SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh = ss.getSheetByName('Database');
var rg=sh.getRange(1,1,sh.getLastRow()-1,4);
var vA=rg.getValues();
var str = "Approved";
for(var i=0;i<vA.length;i++)
{
if(vA[i][3]+" REQ ID: "+vA[i][0] == value) {
sh.getRange(i+1, 2).setValue(str);
}
};
return ContentService.createTextOutput(JSON.stringify({message: "ok"})).setMimeType(ContentService.MimeType.JSON);
Now I am trying to regenerate the drop down list values after the button is clicked. I tried to add
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
in yourServerSideFunc(body) function to regenerate the HTML but does not work. I have tried to force a HTML refresh, but also did not work.
How can I easily re-trigger the generation of the drop down list items? Worst case scenario it is ok to refresh the whole page, but it should be simple to regenerate the drop down list since I have already the code for it.
I ended up with this work around.
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
//ADDED:
var select = document.getElementById("sel1");
select.options[index] = new Option("Approved! Please refresh","Approved! Please refresh");
selectElem.selectedIndex = index;
}
}
It does not really meet the original goal to refresh the list from the sheet. It would be great if someone else posted a solution to call the server function. I tried to add google.script.run.doGet() and similar, but it seems that it does not call the server side functions properly.
I have a shopping Cart on my first page and all the items that have been selected I want it to be shown when user go to the other page.
I'm new in javascript that's why I couldn't figure out how to save those data in local storage. The main thing for me now is how to save the quantity that is being incremented.
NOTE: I'm using one script for two pages.
// this below function is executed when user on page ONE click on the button the quantity increase.
function addtocartbtnclicked(event) {
var button = event.target;
var shopitem = button.parentElement.parentElement;
var title = shopitem.querySelectorAll('h1')[0].innerText;
var price = shopitem.querySelectorAll('.card .price')[0].innerText;
var imgsrc = shopitem.querySelectorAll('.card .my-img')[0].src;
console.log(title, price, imgsrc);
additemtocard(title, price, imgsrc);
updatetotal();
quantityupdate();
}
// this function increase the quantity
function quantityupdate() {
var div = document.querySelectorAll('.each-cart-row');
var qtytotal = 0;
for (var i = 0; i < div.length; i++) {
var card = document.querySelectorAll('.add-to');
card = 1;
qtytotal = qtytotal + card;
}
console.log(qtytotal);
var count = document.querySelector('.totalqty').innerText = qtytotal;
}
var jsonStr = JSON.stringify(quantityupdate());
localStorage.setItem("cart", jsonStr);
// this function is for page TWO where another item will be added when the button is clicked
function addtocartbtnclickedpagetwo() {
var pageimg = document.querySelectorAll('.exzoom_img_ul img')[0].src;
var pagetitle = document.querySelector('#upper-area h3').innerText.slice(62);
var pageprice = document.querySelector('#last-list #product-total').innerText;
var pageqty = document.querySelector('#myform #input-number').value;
console.log(pageimg, pagetitle, pageprice, pageqty);
addtocartitempage(pageimg, pagetitle, pageprice, pageqty);
updatetotal();
var cartValue = document.querySelector('.totalqty')
cartValue = localStorage.getItem("cart");
var cartObj = JSON.parse(cartValue);
}
try to edit quantityupdate function so it actually saves qtytotal variable value to local storage:
function quantityupdate() {
var div = document.querySelectorAll('.each-cart-row');
var qtytotal = localStorage.getItem( "cart") || 0;
for (var i = 0; i < div.length; i++) {
var card = document.querySelectorAll('.add-to');
card = 1;
qtytotal = qtytotal + card;
}
localStorage.setItem( "cart", qtytotal);
var count = document.querySelector('.totalqty').innerText = qtytotal;
return
}
After creating new classroom, the data will then be send to a list as shown on the
IMG 1:
Now, how do I add/make (a) link/s into every classroom so that whenever I click it it will redirect me to a page and show me their specific data like ClassroomID, students, etc.
here's the code:
//retrieving
var userRef = firebase.database().ref().child('Classes' + '/' + user.uid);
userRef.on('child_added', function(data) {
var roomNames = data.val().TheClass;
var ul = document.createElement('ul');
document.getElementById('myList').appendChild(ul);
var li = document.createElement('li');
ul.appendChild(li);
Object.keys(roomNames).forEach(function(key) {
li.innerHTML += roomNames[key];
});
});
//adding
function classcreation(q) {
var checkcn = document.getElementById('classroomName').value;
if (checkcn == "" && checkcn == null) {
alert("Empty Class Name!!");
} else {
var usuid = generateId();
var myClasses = {};
myClasses.TheClass = document.getElementById('classroomName').value;
myClasses.Teacher = user.displayName;
myClasses.TeacherID = user.uid;
myClasses.ClassID = usuid;
fbclass.child(user.uid).push().set(myClasses);
}
}
You can specify like this:
<li>BSIT</li>
<li>BSCS</li>
<li>BSCE</li>
Here, redirect is the partial html where you will land after click on list item text..
I hope this will be helpful to you