how to check if an item exist in sessionstorage? - javascript

I am creating a web page where the user can add an item into a dropbox buy clicking a button. The sessionstorage store the partnum and quantity of the item. The dropbox will display the details (quantity would be 1)of the item selected. How do I update the quantity to 2 if the same item is selected?
$("#btnBuy0").click(function()
{
$("#dropbox").append('<span><img class = "thumb" src="../images/21_metoyou.jpg" />' + teddy[0].desc + ", Price £"
+ teddy[0].price + ", Quantity: " + quantity + "</span><br/>");
if (Modernizr.sessionstorage)
{ // check if the browser supports sessionStorage
myids.push(teddy[0].partnum + quantity); // add the current username to the myids array
sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage
}
else
{
// use cookies instead of sessionStorage
}
for (var item =0; item<sessionStroage.length; item++)
{
var key = sessionStorage.key(teddy[0].partum);
if (teddy[0].partnum == teddy[item].partnum)
{
var q = sesstionStorage.getItem(quantity, quantity++);
}

I would suggest you make use of a differnt data structure for storing the user's basket. Instead of using an Array (myids), you could make use of an Associative Array (by using a JavaScript object) to map the partnum against a quantity, eg:
// Basket is initially empty.
basket = {};
function saveOrder(teddy, quantity) {
var partnum = teddy[0].partnum;
// Create a mapping between the partnum and the quantity
basket[partnum] = quantity;
// Write the basket to sessionStorage.
sessionStorage.basket = JSON.stringify(basket);
}
Using a map would allow you to create helper methods to read and write the basket object from SessionStorage, eg:
function fetchBasketFromSession() {
return JSON.parse(sessionStorage.basket);
}
function writeBasketToSession(basket) {
sessionStorage.basket = JSON.stringify(basket)
}
function getPartNumOf(teddy) {
return teddy[0].partnum;
}
function getQuantityInSessionBasketOf(teddy) {
// Fetch the basket from sessionStorage
var sessionBasket = fetchBasketFromSession(),
partnum = getPartNumOf(teddy);
// Return the quantity mapped to the partnum in the basket, or 0 if nothing
// is mapped.
return sessionBasket[partnum] || 0;
}
// Combining these functions would allow you to update the users basket.
function addToBasket(teddy, quantityToAdd) {
var sessionBasket = fetchBasketFromSession(),
currentQuantity = getQuantityInSessionBasketOf(teddy),
partnum = getPartNumOf(teddy);
// Update the quantity for this partnum and write it back out.
sessionBasket[partnum] = currentQuantity + quantityToAdd;
writeBasketToSession(sessionBasket);
}
Hope that helps :)

Related

save informations in localstorage

i have 5 items in my page with 3 information. (for example, name and price and number )
i want when i click on them (for example item 1) for first time, create an object and save items information to localStorage and for another times increase the number of item in localstorage.
function() {
items.forEach(function(btn) {
btn.addEventListener('click', function(event) {
let exist = localStorage.getItem('name');
var name =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[0].textContent;
localStorage.setItem('name', name);
var price =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[2].textContent;
localStorage.setItem('price', price);
var number = localStorage.getItem('number');
number = parseInt(number);
if (number) {
localStorage.setItem('number', number + 1);
} else {
localStorage.setItem('number', 1)
}
});
});
})();
its my code, but when i click on any item, previeos details in localstorage will be lost and information of new item replaced.
how i can resolve it?
When you are calling localStorage.setItem('name', name) you are overwriting the previous value of name. To store all names, prices, and numbers you have to use array. But, localStorage supports nothing but string. So before writing, you have to convert the array to a string, and upon reading you have to revert the string back to an array.
function() {
items.forEach(function(btn) {
btn.addEventListener('click', function(event) {
let names = localStorage.getItem('name');
const exists = !!names;
names = exists ? JSON.parse(names) : [];
let prices = exists ? JSON.parse(localStorage.getItem('price')): [];
let numbers = exists ? JSON.parse(localStorage.getItem('number')) : [];
var name =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[0].textContent;
const nI = names.indexOf(name);
if (nI === -1) {
names.push(name);
localStorage.setItem('name', JSON.stringify(names));
var price =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[2].textContent;
prices.push(price);
localStorage.setItem('price', JSON.stringify(prices));
numbers.push(1);
} else {
// else they are already in localStorage, just increase number
numbers[nI]++;
}
localStorage.setItem('number', JSON.stringify(numbers));
});
});
})();

Array.push is not working for local storage

I am creating a shopping cart where user can add an item to cart. Once user clicked the addtocart button, I want to save the product id, name, price and quantity to local storage and then retrieve them on the cart page. So I tried this
var cart = new Array;
if (cart != []) {
cart = JSON.parse(localStorage["cart"]);
}
$('#addtocart').on('click', function(e) {
var qty = document.getElementById("p-qty").value;
var li = $(this).parent();
var product = {};
product.id = productid;
product.name = document.getElementById("nomenclature").innerHTML;
product.price = document.getElementById("productprice").innerHTML;
product.quantity = qty;
addToCart(product);
});
function addToCart(product) {
// Retrieve the cart object from local storage
if (localStorage) {
var cart = JSON.parse(localStorage['cart']);
cart.push(product);
localStorage.setItem('cart', JSON.stringify(cart));
}
// window.location = "html/cart.html"
}
but I keep getting this error
Uncaught TypeError: cart.push is not a function
What am I doing wrongly and how can I fix it?
You don't check that localStorage['cart'] is defined and don't check that the deserialized variable is an array. I'd suggest doing something like this:
function addToCart(product) {
if (localStorage) {
var cart;
if (!localStorage['cart']) cart = [];
else cart = JSON.parse(localStorage['cart']);
if (!(cart instanceof Array)) cart = [];
cart.push(product);
localStorage.setItem('cart', JSON.stringify(cart));
}
}
Note, however, that if you have a serialized object or other non-array variable in localStorage['cart'], it will be overwritten with this method.
localStorage in HTML5 is Object, you can set item by using .setItem() and get item by .getItem()
Demo get old values, push new value and save values with localStorage
var Values = [];
//get olds values
Values = JSON.parse(localStorage.getItem('Storage'));
//push new value
Values.push(item);
//saved values
localStorage.setItem('Storage', JSON.stringify(Values));
Now with your edit, problem you have here is this makes no sense. First You set the array to be empty, so it will always be empty. Now second issue is [] will never equal new Array so it will always go into the if statement. And since you probably never set localStorage["cart"] with anything, it will be invalid.
var cart = new Array; // <-- you define an array?
if (cart != []) { // <- than you check the array you just created? How would it have a value if this check would actually work?
cart = JSON.parse(localStorage["cart"]);
}
So what you need to do is get rid of that if, since it does nothing. Next you just need to check localstorage if it has a value, if it does not, than set it to an emoty array. So add a conditional that if it is undefined, it uses a new array
Now what your codde should have been was
var cart = []; //define the array
if (localStorage["cart"]) { // Check that it has a value in storage
cart = JSON.parse(localStorage["cart"]); //If yes, parse it
}
or another way could be
var cart = JSON.parse(localStorage['cart'] || '[]');

JQuery to update the HTML of a div without reloading page

I have a div that is displaying the contents of an order. Currently this is how I am implementing adding items to this div using JQuery
$(document).ready(function(){
//if cookie exists, show the panel
if($.cookie('order_cookie') != undefined){
productArray = JSON.parse($.cookie('order_cookie'));
$(".order-alert").show();
for(var i = 0; i < productArray.length; i++){
console.log(productArray[i]);
var obj = productArray[i];
$(".order-alert").append("<p> StockCode: " + obj.stockCode + " Qty: " + obj.quantity + "</p>");
console.log("Object code: " + obj.stockCode + " Qty: " + obj.quantity);
}
$('#order_counter').html(productArray.length);
}
});
I have it working so that when the user adds an item to the order the counter increments without reloading the browser window.
$('#order_counter').html(productArray.length);
I'm just wondering how I could implement the same thing with my loop to output the items in the order as the user adds them to the array
Any help is greatly appreciated.
This script adds items to array, the cookie is also set in the script
var productArray = []; // Will hold order Items
$(".orderBtn").click(function(event){
//Check to ensure quantity > 0
if(quantity == 0){
console.log("Quantity must be greater than 0")
}else{//It is so continue
//Show the order Box
$(".order-alert").show();
event.preventDefault();
//Get reference to the product clicked
var stockCode = $(this).closest('li').find('.stock_code').html();
//Get reference to the quantity selected
var quantity = $(this).closest('li').find('.order_amount').val();
//Order Item (contains stockCode and Quantity) - Can add whatever data I like here
var orderItem = {
'stockCode' : stockCode,
'quantity' : quantity
};
//Check if cookie exists
if($.cookie('order_cookie') === undefined){
console.log("Creating new cookie");
//Add object to the Array
productArray.push(orderItem);
}else{//Already exists
console.log("Updating the cookie")
productArray = JSON.parse($.cookie('order_cookie'));
//Check if the item already exists in the Cookie and update qty
var found = false;
for(var i =0; i < productArray.length; i++){
if(productArray[i].stockCode == stockCode){
console.log("OBJECT EXISTS")
var index = i;
found = true;
}
}
//If it exists update the old quantity
if(found){
//update
console.log("Match found at: " + index);
var oldQty = (productArray[index].quantity)
var newQty = parseInt(quantity) + parseInt(oldQty);
productArray[index].quantity = newQty;
}else{// It doesn't exist so add new item to array
productArray.push(orderItem);
}
}
}
//Update the Cookie
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
//Testing output of Cookie
console.log($.cookie('order_cookie'));
//Update the order tracker
$('#order_counter').html(productArray.length);
});
I can think of two options:
1) Create another field for the order to print them in which you update when a user adds something to their order.
2) Implement the move to front heuristic on your product array so that when a product is incremented it's moved to the front of the array and the products originally in front of it are pushed back one space. As an example if you start with
"orange" => 1
"pear" => 1
and then the user adds a pear followed by an apple, the result would be:
"apple" => 1
"pear" => 2
"orange" => 1
Both have issues when the array gets massive, but if you won't be getting orders containing hundreds of unique products, it shouldn't be an issue.
Regardless of which method you use, you can update the list presented to the user by just using $('.order-alert').prepend()

search history with localStorage variable in HTML

I'm creating an jQuery mobile app with PhoneGap and I want to list old search results (entered by a form and stored in localStorage).
There are two different problems to solve:
1) I would store a result in a localStorage array and if the user is searching a second time, the result should be added to the array after the old result like: city[0] = "New York", city[1] = "Paris" ... how can I save and read a string in an array, like:
localStorage.setItem('city[i]', $('#city').val());
or
localStorage.getItem('city[i]');
2) Now I want to show the search history. I've tried this, but:
I don't know how to display the localStorage array or variable in a html list and ...
if no variable in localStorage, the website doesn't load.
<div id="lastResults"></div>
<script>
var history = "";
if (localStorage.getItem("history") !== "") {
var history = localStorage.getItem("history");
}
if ( history !== "") {
$("#lastResults").html(
"<b>Last Results:</b>" +
"<ul data-role=\"listview\" data-inset=\"true\" >" +
"<li> " + document.write(history) + " </li>" +
"</ul>"
);
}
</script>
LocalStorage stores key value pairs where both the key and the value are strings. One way to get around this is to use a JSON object to store your data and use JSON.stringify and JSON.parse to change the data from object to string and back.
EXAMPLE:
var historyObj = { city: [] };
function onLoad() {
if(localStorage.getItem('history')) {
historyObj = JSON.parse(localStorage.getItem('history'));
}
}
function addHistory(dataToSave) {
historyObj.city.push(dataToSave);
localStorage.setItem('history',JSON.stringify(historyObj));
}
<div id="lastResults"></div>
<script type="text/javascript">
//To Check and show previous results in **lastResults** div
if (localStorage.getItem("history") != null)
{
var historyTmp = localStorage.getItem("history");
var oldhistoryarray = historyTmp.split('|');
$('#lastResults').empty();
for(var i =0; i<oldhistoryarray.length; i++)
{
$('#lastResults').append('<p>'+oldhistoryarray[i]+'</p>');
}
}
//Storing New result in previous History localstorage
if (localStorage.getItem("history") != null)
{
var historyTmp = localStorage.getItem("history");
historyTmp += '|Paris|Pakistan|China|US';
localStorage.setItem("history",historyTmp);
}
else
{
var historyTmp = 'Paris|Pakistan|China|US';
localStorage.setItem("history",historyTmp);
}
</script>
Note I have used jquery for code shortening.

how to remove concatenated data in localStorage

I'm using localStorage to store some data and all the data are concatenated separated by \n. I want to remove specific data in localStorage and i'm using listbox to display all the data.
example {"rowdata":"data1\ndata2\ndata3"} // the three data are stored in localStorage, the key of rowdata in the localStorage is storedata and the rowdata is the value of storedata that have three data concatenated.
is there an easy way to remove the selected data, example i want to remove data3. i'm using google chrome browser..
code for display:
function populate(){
for(i=0; i<rowdata.length; i++){
var select = document.getElementById("test"); // id of the listbox
var splitRow = rowdata.split("\n");
var row = splitRow[i];
if(row != undefined)
select.options[select.options.length] = new Option(row);
}
}
code for remove:
function removeSelectedItem(){
var htmlSelect=document.getElementById('test'); // id of the listbox
if(htmlSelect.options.length == 0)
{
alert('You have already removed all list items');
return false;
{
var optionToRemove = htmlSelect.options.selectedIndex;
htmlSelect.remove(optionToRemove);
if(htmlSelect.options.length > 0)
{
htmlSelect.options[0].selected=true;
{
alert('The selected data has been removed successfully');
return true;
}
Thanks...
Not sure if I clearly understood the question, but if you just need to update state if rowdata variable then try put the code below before removing an option from select in RemoveSelectedItem (man, start function names with lowercase!):
rowdata = ("\n" + rowdata + "\n").replace("\n" + htmlSelect.options[htmlSelect.options.selectedIndex].innerHTML + "\n", "").trim()

Categories