How to use local Storage to show data on other page - javascript

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
}

Related

Shopping Cart Items JS

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

How to remove items from an array on a checkout page

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
}

Google script - parse HTML from Website Forum - and Write Data to Sheet

I'm getting HTML from a forum url, and parsing the post count of the user from their profile page. I don't know how to write the parsed number into the Google spreadsheet.
It should go account by account in column B till last row and update the column A with count.
The script doesn't give me any errors, but it doesn't set the retrieved value into the spreadsheet.
function msg(message){
Browser.msgBox(message);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Update")
.addItem('Update Table', 'updatePosts')
.addToUi();
}
function getPostCount(profileUrl){
var html = UrlFetchApp.fetch(profileUrl).getContentText();
var sliced = html.slice(0,html.search('Posts Per Day'));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
return postCount;
}
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var accountSheet = spreadSheet.getSheetByName("account-stats");
var statsLastCol = statsSheet.getLastColumn();
var accountCount = accountSheet.getLastRow();
var newValue = 0;
var oldValue = 0;
var totalNewPosts = 0;
for (var i=2; i<=accountCount; i++){
newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue()));
oldValue = parseInt(accountSheet.getRange(i, 7).getValue());
totalNewPosts = totalNewPosts + newValue - oldValue;
accountSheet.getRange(i, 7).setValue(newValue);
statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue);
}
if(showAlert==false){
return 0;
}
msg(totalNewPosts+" new post found!");
}
function valinar(needle, haystack){
haystack = haystack[0];
for (var i in haystack){
if(haystack[i]==needle){
return true;
}
}
return false;
}
The is the first time I'm doing something like this and working from an example from other site.
I have one more question. In function getPostCount I send the function profileurl. Where do I declare that ?
Here is how you get the URL out of the spreadsheet:
function getPostCount(profileUrl){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("List1");
var getNumberOfRows = thisSheet.getLastRow();
var urlProfile = "";
var sliced = "";
var A_Column = "";
var arrayIndex = 0;
var rngA2Bx = thisSheet.getRange(2, 2, getNumberOfRows, 1).getValues();
for (var i = 2; i < getNumberOfRows + 1; i++) { //Start getting urls from row 2
//Logger.log('count i: ' + i);
arrayIndex = i-2;
urlProfile = rngA2Bx[arrayIndex][0];
//Logger.log('urlProfile: ' + urlProfile);
var html = UrlFetchApp.fetch(urlProfile).getContentText();
sliced = html.slice(0,html.search('Posts Per Day'));
var postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
Logger.log('postCount: ' + postCount);
A_Column = thisSheet.getRange(i, 1);
A_Column.setValue(postCount);
};
}
You're missing var in front of one of your variables:
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
That won't work. Need to put var in front. var postCount = ....
In this function:
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
There is no array named arguments anywhere in your code. Where is arguments defined and how is it getting any values put into it?

Can't get form total cost

So I have a form with two dropdowns. The first dropdown is the options, and the other is more options. So it's like a mix and match, now I want to calculate the total from the two selected dropdowns. Here's what I got going
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
$("#repair_drop").change(function (event) {
getRepair();
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair
}
});
$("#colorize_drop").change(function (event) {
getColor();
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color
}
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}
total();
I end up getting
Uncaught ReferenceError: getRepair is not defined
So for example I'd choose repairCost["minor"] and colorCost["group_scene"], then my result would be $30. I have a timer in there so it automatically calculates the total. Any ideas?
You defined the getRepair function inside another function. Therefore you cannot access it from outside. You have to define it outside the function to be able to access it, like so :
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair;
}
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color;
}
$("#repair_drop").change(function (event) {
getRepair();
});
$("#colorize_drop").change(function (event) {
getColor();
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}
Why are you declaring functions within your events, and then calling them from there? Either declare them outside the events, or just inline the code - don't do both.

How to change the flow of execution and function call in this Google Apps Script?

I have a main function generatePersonDatasheet(theses) and I have a handler function submit(e) (the handler is in other function called showList()).
In the main function, I can call the handler function this way:
if (theses == 1){
Logger.log("going to showList() ");
return showList();
If I drop de return in the line return showList(); the UI of showList() opens and closes at a fraction of second, not allowing the user choose the items. If I put this return, after the handler function submit(e) is closed, the code in my main function doesn't run the next line after the if block:
if (theses == 1){
Logger.log("going to showList() ");
return showList();
}
showURL(docName, link); // Shows document name and link in UI
How could I fix that? How could I got the main function to runs its lines after the if (theses == 1) block? I didn't want to repeat the code in the handler function because it's bigger than the line showURL(docName, link); in the above sample.
This is the called functions:
var fact_list = [ ["Kennedy Inauguration", "politics", "tZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf"], ["Pericles’ Funeral Oration", "politics", "sdgrewaNkNklYc3pVUzZINUV4eUtW345ufaZ"], ["The Pleasure of Books", "culture", "1234rFszdgrfYc3pVUzZINUV4eU43usacd"], ["I Am The First Accused (Nelson Mandela)", "law", "34rsgadOsidjSZIswjadi95uydnfklsdks"] ];
function showList() {
Logger.log("running showList ");
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
// Store the number of items in the array (fact_list)
Logger.log("fact_list.length " + fact_list.length);
panel.add(app.createHidden('checkbox_total', fact_list.length));
// add 1 checkbox + 1 hidden field per item
for(var i = 0; i < fact_list.length; i++){
Logger.log("checkbox_isChecked_"+i + " = " + fact_list[i][0]);
Logger.log("checkbox_value_"+i + " = " + fact_list[i]);
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i][0]);
var hidden = app.createHidden('checkbox_value_'+i, fact_list[i]);
panel.add(checkbox).add(hidden);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
app.add(panel);
mydoc.show(app);
}
function submit(e){
Logger.log("running submit(e)");
var numberOfItems = e.parameter.checkbox_total;
var itemsSelected = [];
// for each item, if it is checked / selected, add it to itemsSelected
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
itemsSelected.push(e.parameter['checkbox_value_'+i]);
}
}
var app = UiApp.getActiveApplication();
Logger.log("itemsSelected = " + itemsSelected);
ScriptProperties.setProperties({'theses': itemsSelected}, true);
var thesesArrays = ScriptProperties.getProperty('theses');
Logger.log("thesesArrays = " + thesesArrays);// to see targetDoc's content
for (var i = 0; i < thesesArrays.lenght; i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
app.close();
return app;
}
function importTheses(targetDocId, thesesId, thesesType) { // adapted from Serge insas
Logger.log("running importTheses() ");
var targetDoc = DocumentApp.openById(targetDocId);
var targetDocParagraphs = targetDoc.getParagraphs();
var targetDocElements = targetDocParagraphs.getNumChildren();
var thesesDoc = DocumentApp.openById(thesesId);
var thesesParagraphs = thesesDoc.getParagraphs();
var thesesElements = thesesDoc.getNumChildren();
var eltargetDoc=[];
var elTheses=[];
for( var j = 0; j < targetDocElements; ++j ) {
var targetDocElement = targetDoc.getChild(j);
// Logger.log(j + " : " + type);// to see targetDoc's content
eltargetDoc[j]=targetDocElement.getText();
if(el[j]== thesesType){
for( var k = 0; k < thesesParagraphs-1; ++k ) {
var thesesElement = thesesDoc.getChild(k);
elTheses[k] = thesesDoc.getText();
targetDoc.insertParagraph(j, elTheses[k]);
}
}
}
}
Please have a look at this worflow, wouldn't it be more easy ?
(check the log to confirm the last function was called)
note : I didn't use scriptProperties as it was not necessary anymore since factList is a global variable in your example... and I simplified the importTheses function for this test since I had no docs to use ;-)
var fact_list = [["Kennedy Inauguration", "politics", "tZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf"], ["Pericles Funeral Oration", "politics", "sdgrewaNkNklYc3pVUzZINUV4eUtW345ufaZ"], ["The Pleasure of Books", "culture", "1234rFszdgrfYc3pVUzZINUV4eU43usacd"], ["I Am The First Accused (Nelson Mandela)", "law", "34rsgadOsidjSZIswjadi95uydnfklsdks"]];
function showList() {
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
// Store the number of items in the array (fact_list)
panel.add(app.createHidden('checkbox_total', fact_list.length));
// add 1 checkbox + 1 hidden field per item
for(var i = 0; i < fact_list.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i][0]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
app.add(panel);
mydoc.show(app);
}
function submit(e){
var numberOfItems = Number(e.parameter.checkbox_total);
var thesesArrays = [];
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
thesesArrays.push(fact_list[i]);
}
}
Logger.log(thesesArrays);
var target = 'target doc';
for (var i = 0; i < thesesArrays.length; i++){
var thesesId = thesesArrays[i][2];
var thesesType = thesesArrays[i][1];
importTheses(target, thesesId, thesesType);
}
// showURL(docName, link); /
return UiApp.getActiveApplication().close();
}
function importTheses(targetDocId, thesesId, thesesType) { // adapted from Serge insas
Logger.log(targetDocId+' '+thesesId+' '+thesesType);
}

Categories