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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.