JavaScript - Cookies For Shopping Cart
Hi and hope someone can help,
I'm doing some course work on setting / getting cookies for a shopping cart. It basically works except the user can only select one item of each of the goods on offer i.e. you can only buy one cup (not two), one saucer etc. etc. I've deliberately not put a quantity field on the goods selection page and was hoping to modify my set cookie function so that if you've already selected one cup, the next tiume you select a cup, cups become 2 etc. etc. Here's my set cookie function. Notice that I've hard wired a "1" in there which I want to change to the variable for the number of cups. I've also commented out some of the first few lines which were experiments to resolve the problem. Code: function setCookie(name) { alert("Thank you.\n\nYour basket has been updated."); /* if(name.value !=0 || name.value==null) name.value++; x=getCookie(name) || 0; alert(document.cookie);*/ var today = new Date(); var expiry = new Date(today.getTime()+28*24*60*60*1000); // plus 28 days document.cookie=name+"= 1 ;expires="+expiry.toGMTString(); cart = document.cookie; } My thanks, R A little while later... I've cracked it, my function now looks like this and it appears to work... Code: function setCookie(name) { alert("Thank you.\n\nYour basket has been updated."); x=parseInt(getCookie(name)) || 0; alert(x); y=x+1; var today = new Date(); var expiry = new Date(today.getTime()+28*24*60*60*1000); // plus 28 days document.cookie=name+"="+y+";expires="+expiry.toGMTString(); cart = document.cookie; } Thanks you fror your interest, appreciated, R Similar TutorialsI am working on my shopping cart page with DOM. In my html I created two tables one for items with add buttons, and the other one for displaying how many items are added. So, here is my html codes Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="description" content="forms" /> <meta name="keywords" content="Client Side Programming, JavaScript, CSS" /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Language" content="en-us" /> <script type="text/javascript" src="shopping.js"></script> </head> <body> <h1>Central Valley Chocolates</h1> <h2>Gourmet Chocolates</h2> <table border="1" id="chocoateTrable"> <tr id="ch1"> <td>Chocolate Truffles</td><td>$34.99</td><td> <input type="button" value="Add" onclick="addItem(document.getElementById('ch1').rowIndex)" /></td></tr> <tr id="ch2"> <td>Pecan</td><td>$14.99</td><td> <input type="button" value="Add" onclick="addItem(document.getElementById('ch2').rowIndex)" /></td></tr> <tr id="ch3"> <td>Truffles</td><td>$28.99</td><td> <input type="button" value="Add" onclick="addItem(document.getElementById('ch3').rowIndex)" /></td></tr> <tr id="ch4"> <td>caramel</td><td>$22.99</td><td> <input type="button" value="Add" onclick="addItem(document.getElementById('ch4').rowIndex)" /></td></tr> <tr id="ch5"> <td>Bark</td><td>$17.99</td><td> <input type="button" value="Add" onclick="addItem(document.getElementById('ch5').rowIndex)" /></td></tr> </table> <h2>Your Shopping Cart</h2> <table id="shoppingCart" border="1"> <tr><td>Your shopping cart is empty</td></tr> </table> <p id="total"> </p> </body> </html> And in my js file, I have two functions one for adding items and the other for deleting items. Code: var emptyCart = true; var salesTotal = 0; var curRow = 1; function addItem(selectedItem){ if(emptyCart == true){ document.getElementById('shoppingCart').deleteRow(0); emptyCart = false; } var curItem = document.getElementById("chocolateTable").rows[selectedItem].cells; var selectedItem = curItem[0].innerHTML; var itemPrice = curItem[1].innerHTML; var lastItem = document.getElementById("shoppingCart").rows.length; var cartTable = document.getElementById("shoppingCart"); var newRow = cartTable.insertRow(lastItem); document.getElementById("shoppingCart").rows[lastItem].id = "R" + curRow; var itemCell = newRow.insertCell(0); itemCell.innerHTML = selectedItem; var priceCell = newRow.insertCell(1); priceCell.innerHTML = itemPrice; var actionCell = newRow.insertCell(2); actionCell.innerHTML = "<input type='button' value = 'Remove' " + "onclick=\"removeItem('R"+curROw + "')\" />"; ++curRow; salesTotal += parseFloat(itemPrice.substring(1)); document.getElementById('total').innerHTML = "<strong>Sales total</strong>: $" + salesTotal.toFixed(2); } function removeItem(rowNum){ if(document.getElementById("shoppingCart").rows.length == 1){ document.getElementById("shoppingCart").rows[0].cells[0].innerHTML = "<td>Your shopping cart is empty</td>"; document.getElementById("shoppingCart").rows[0].cells[1].innerHTML = "<td>$0.00</td>"; document.getElementById('total').innerHTML = "$" + salesTotal.toFixed(2); emptyCart = true; } else{ var selectedRow = document.getElementById(rowNum).rowIndex; var itemPrice = document.getElementById("shoppingCart").rows[selectedRow].cells[1].innerHTML; document.getElementById("ShoppingCart").deleteRow(seletedRow); salesTotal = salesTotal - parseFloat(itemPrice.substring(1)); document.getElementById('total').innerHTML = "$" + salesTotal.toFixed(2); } } However, when I click add button to add each item, I don't see anything in my shoppingCart. Anyone can tell me what is wrong with my code? Hi all, I have just joined this forum hoping for some help on a problem i am having, i have a feeling the solution is simple but im a noob at JAVA so i have no idea how to work it out. The site is.... http://inspirecalendar.net/html/purchase.html The problem is the following.... When you select US (West Coast) as your location it doesn't update the price on the right properly. If you select it first it just won't display anything. if you select it after choosing another one and hitting continue then it doesn't change. Any help would be appreciated, hope i explain the problem properly if you have any questions feel free to ask... Thnks in advance :Smiley I'm using simpleCart.js (http://simplecartjs.com ) on http://yogasports.biz and have run into issues. I would like the checkout page to allow items to be removed or quantities edited and it is currently not allowing it. The javascript is located at http://yogasports.biz/simpleCart.js Also there are additional shipping options that are not appearing upon checkout yet they are declared in the paypal account. I'm unsure of what to edit in the javascript file so that they will appear. Hello guys my question has changed, i dont want to double post so here is my new question, I now have 3 arrays name price quantity totalPrices now i want to create a table that will hold them but it will be created when you click the shop cart button, this button will take you to a blank page with the table on it i would like something like this Toy name| Quantity | Price | Total price Toy1 | Quantity | Price | Total price of that toy Toy2 | Quantity | Price | Total price of that toy Toy3 | Quantity | Price | Total price of that toy ----- | -------- | ----- | Total price all together I have looked at many tutorials but i cant get any to work, all they do is draw nothing and i cant get it to work Hi Guys, I am trying to get the Fat-Free shopping cart woking with a flash file. I have tried [CODE] on (rollOver) { _parent.gotoAndPlay("s1"); } on (releaseOutside, rollOut) { _parent.gotoAndPlay("s2"); } on (release) {getURL("https://www.e-junkie.com/ecom/fgb.php?c=cart&cl=1&ejc=2&merchant_id=your_google_merchant_id&business=website.com" target="ej_ejc" class="ec_ejc_thkbx" onClick="javascript:return EJEJC_lc(this));"}[CODE] The compiler tells me that a ')' or ',' is expected. Any help appreciated. I am a newbie. Thanks PeterW hello recently i finally managed to make a working shopping cart system, in that i can add as many items as i want and it will work, all using cookies. Then i have another page, the cart which reads the cookie entry made with each demo purchase, then using a while loop lists these items, the problem i am having, is that when i add the textbox which would hold the value of the quantity, it is put out on the next line down, instead of next to the text which i find quite annoying. Also i would like to know how i can add a button next to the textbox, for updating the quantity, also ide like to know how i could access that button, or have it do something, since it wouldnt be prewritten. any help would be greatly apreciated. here is a zip file containing the html files of the customizable purchase page, and the new shopping cart. be sure to refresh the page before trying to use the first page, so it establishes the counter cookie. Hi All! Thanks in advance to any and all who help me. What we are trying to do is have a form where customers can use a conditional logic based form that upon submission will redirect to checkout with an appropriate product bundle being populated in the shopping cart. I have some experience with creating forms, in fact I have made a decent form that I have modified from an online form builder... the problem is I have no idea how to auto-fill the shopping cart... period. From what I have read in my research this should be a function of Javascript. I have a decent working knowledge of php, and html, but I am pretty clueless when it comes to Javascript, if anyone could point me in the right direction for this project I would really appreciate it. I've been given this ridiculous assignment where I have to create a shopping web page. I really need help finding the javascript codes that will allow the user to update their total as they enter the quantities of the different products in the assigned text boxes. I don't even know where to start because we were never taught how to do this in class! I am looking for help to develop a java code for my e-commerce site mini cart. I have looked locally (kijiji) and on Coding Forums market place and haven't received a great response. Either the person had other projects they were working on or they were trying to "sell" me more than what I was asking for (ie web and graphic design). I have a mini cart on my site that I would like to have a few specific features. I am hoping someone in this forum can help me out (as I have received wonderful help before!!) I need a javascript code/feature that will: - highlight the most recent item that has been added to slide down mini cart window - refresh the mini cart div content to update item count and price. On the site I am hosted on there is a built in feature to show how many items are in the cart and total price, but I don't know how to get it to update successfully - when slide down mini cart window refreshes it should'nt scroll to the top (if there is a scrollbar) ie: looking to implement a javascript: void (0) if possible - have the slide down minicart window appear for 5-10 seconds then automatically slide back up. (the visitor can also have the option to close the window before the 5 seconds) I would really appreciate any help with this. I find javascript hard and I have tried to learn it, but unfortunately I can't seem to grasp it . Right now this javascript shopping cart works to 1. charge shipping based on the item, 2. the destination country, 3. it combines shipping for a quantity over 1 of the SAME item. Each item has 2 different possible shipping charges. I am trying to get the javascript to check the shopping cart to see what item in the cart has the highest possible shipping charge, charge that amount to that item, and charge the lowest possible shipping charge on all other items in the cart. If item A is purchased alone shipping is $5.00. If purchased with item B, which costs $10.00 to ship alone, the $10.00 is charged for item B and only $3.00 for item A. Because item B had the higher shipping charge at a quantity of one. I have tried adding various things like me.items[current], item.shipping, me.shipping, this.shipping, shipping_Cost, and other things next to the second && in the part of the script that shows the country. I have also tried adding && if (me.whatever) and && if (item.whatever) and similar things at the beginning of the script next to if (this.country). I have found the parts of the script that pertain to cart items and to updating the shopping cart. Now I am stuck. The javascript is in 2 parts. One part goes in the item page, which I will post first. The second part goes in an external javascript file which I will post at the bottom. In between there is the part that shows the shopping cart. It isn't part of the javascript. Code: <script type="text/javascript" src="simpleCart.js"></script> <script type="text/javascript"> <!-- simpleCart.checkoutTo = PayPal; simpleCart.email = "my Paypal email address"; simpleCart.cartHeaders = ["Name" , "Price" , "Quantity" , "remove" ]; CartItem.prototype.shipping=function(){ // we are using a 'country' field to calculate the shipping, // so we first make sure the item has a country if(this.country){ if( this.country == 'United States' && this.quantity == '1'){ return this.quantity*5.00; } else if( this.country == 'United States' && this.quantity >= '2') { return this.quantity*3.00; } else if( this.country == 'Belgium' && this.quantity == '1') { return this.quantity*12.00; } else if( this.country == 'Belgium' && this.quantity >= '2') { return this.quantity*9.00; else { return this.quantity*0.00; } } else { // use a default of $0.00 per item if there is no 'country' field return this.quantity*0.00; } } // --></script> Code: <div style="display:block;"></div> <div>SHOPPING CART</div> <div class="cartHeaders"></div><br><br><br> <div class="simpleCart_items"></div> <div id="totals"> Item Total: <span class="simpleCart_total"></span><br>Shipping Total: <span class="simpleCart_shippingCost"></span><br>Tax: <span class="simpleCart_taxCost"></span><br>Final Total: <span class="simpleCart_finalTotal"></span> </div> <br><br><br><br> <br><br> <a href="javascript:;" class="simpleCart_empty">Empty Shopping Cart</a><br><br> <a href="javascript:;" class="simpleCart_checkout">Checkout Through Paypal</a> </div></div> separate javascript file is here http://simplecartjs.com/documentation.html I need help in creating a multiple value cookie when the user clicks the Add to cart input button. Here is the portion of code from the html page that creates the inventory item display and the Add to cart button. There are six of these on the page: Code: <div id="inventoryspread"> <div class='productBoxInvUL'> <script type:"text/javascript"> document.write("<img src="+"'"+"images/"+arrImage[0]+"'"+"align='left'/>"+ "<p><br/><span class='invName'>"+arrName[0]+"</span></p>"+ "<p>"+arrDescription[0]+"</p>"+ "<p>Item# "+arrItem[0]+"<br/>"+ "<span class='invPrice'>"+arrPrice[0]+"</p>"); </script> <input type="button" value="Add to Cart" onclick='createCookie("name, value, 7", prompt("cookie created"))' /> </div> And here is a portion of the array that fills it: Code: var arrItem = new Array(); var arrName = new Array(); var arrDescription = new Array(); var arrPrice = new Array(); var arrImage = new Array(); arrItem[0]= "FE100"; arrName[0]= "Blacktop Jazzmaster"; arrDescription[0]= "Monster dual-bucker tone. Vintage style alnico humbucking pickup, single coil, skirted black amp knobs, and 3-way toggle switch. Alder body, Maple neck, Rosewood fretboard, 21 medium jumbo frets, gloss urethane finish and nickel/chrome hardware."; arrPrice[0]= "$699.00"; arrImage[0]= "FE100.png"; arrItem[1]= "FE200"; arrName[1]= "Roland-Ready Stratocaster"; arrDescription[1]= "Time-tested Fender tone, timeless styling, 3 single-coil pickups, synchronized tremolo, high-mass bridge block, shielded body cavities and medium jumbo frets. Built-in Roland GK-2A pickup system, tinted neck, parchment pickguard and control knobs, and a '70s-style logo."; arrPrice[1]= "$1,019.00"; arrImage[1]= "FE200.png"; arrItem[2]= "FA100"; arrName[2]= "CD220SCE Exotics "; arrDescription[2]= "Exotic and beautiful with rich tone, laminated burl ash back and sides, with a solid spruce top. Fender-designed dreadnought body, X-bracing, and die-cast tuners. Cutaway body design with rosewood bridge featuring a compensated bone nut"; arrPrice[2]= "$629.00"; arrImage[2]= "FA100.png"; arrItem[3]= "FA200"; arrName[3]= "Dick Dale Mailbu SCE"; arrDescription[3]= "Thin folk body design, laminated spruce top, laminated mahogany back and sides, scalloped X-bracing providing well balanced tone. Maple neck, rosewood compensated bridge and fretboard, vintage-style Fender tuners, and a surfin' red paint job on the top and back"; arrPrice[3]= "$849.00"; arrImage[3]= "FA200.png"; arrItem[4]= "FB100"; arrName[4]= "Standard Precision Bass"; arrDescription[4]= "Sound, look, and feel today's bass players demand. Classic P-Bass old-school design. Contemporary features and refinements. Alder body and a split single-coil pickup, this classic electric bass guitar lives up to its Fender legacy."; arrPrice[4]= "$579.00"; arrImage[4]= "FB100.png"; arrItem[5]= "FB200"; arrName[5]= "Roger Waters Signature Precision Bass"; arrDescription[5]= "Tastefully tailored, black-on-black color scheme, Seymour Duncan Basslines SPB-3 Quarter-Pound split-coil Precision Bass pickup, knurled black control knobs, brass nut, black bridge and strap buttons, vintage '70s-style open-gear chrome tuners."; arrPrice[5]= "$1,199.00"; arrImage[5]= "FB200.png"; arrItem[6]= "GE100"; arrName[6]= "Firebird X Limited Edition"; arrDescription[6]= "Turbo-charged Pure-Analog engine. Hand-applied and unique high-end wood finish. Beautiful, historical and yet contemporary and unique. Limited run of just 1,800 units. It is sure to become a collector classic."; arrPrice[6]= "$5,569.00"; arrImage[6]= "GE100.png"; The cookie only needs to include the Item#, Name and Price of each item to populate a shopping cart page. This is only a small student project and is client side only using javascript. Thank you for any help we can get on this. Hello All, So, I have a website with a floating cart and it loads fine and works almost flawlessly lol. However, when a person has a bunch of items in their cart, and they want to minimize it for the rest of their browsing experience, every time a new page loads, or a refresh happens, the floating cart un-minimizes and expands out fully again displaying all the items. This can become very annoying during the shopping experience when you have a bunch of items loading and just taking up space in the browser. Therefore, I am wondering if their is some html or script that would save the minimizing in the floating cart, and carry it over to the next page, and the rest of the browsing on site? Thank you for any suggestions/help. I am new to HTML and script writing, but I am eager to learn. Hopefully in the future, I won't be paying for little changes like this every time I need one. Good morning! Hopefully somebody can help me with this javascript question. (No knowledge of Google Anayltics needed for this.) I'm adding Google Analytics 'Event Tracking' javascript to a typical 'Add to Cart' button. The customer enters desired quantity in the text box and clicks the 'Add to Cart' button to order. I would like to use the Event Tracking javascript to record the button click - plus the Value entered in the text box - as one event. Here's the code for the form (the text box and 'Add to Cart' button code lines are bold): Code: <form method="post" action="http://www.yoursite.com/mm5/merchant.mvc?"> <input type="hidden" name="Screen" value="BASK" /> <input type="hidden" name="Product_Code" value="yourproductcode" /> <input type="hidden" name="Action" value="ADPR" /> <label for="quantity">Quantity:</label> <input type="text" name="quantity" value="0" /> <input type="submit" value="Add To Cart" /> </form> I came up with this javascript for the Event Tracking (to be inserted somewhere above): Code: onClick="_gaq.push(['_trackEvent', 'OrderForms', 'AddToCart', 'yourproductcode', document.getElementByName('quantity').value]);" I'm wondering where I would enter this javacript code inside the form code to pick up both the button click - plus the quantity? You'll notice that I'm using 'getElementByName' to extract 'quantity' from the text box and record its 'value'. If I enter this javascript on the 'Add to Cart' line - right after "Add to Cart", would 'quantity' still get picked up upon button-click - since it's all on the same form? Or would it be a problem because 'quantity' is contained in a different <input> container? Thanks! Any help is greatly appreciated. IB I am trying to combine shipping across different items in a javascript shopping cart. I can comine shipping based on how many items are in the cart, and characteristics of the item being added. But not both. I need the script to combine shipping based on how many items are in the cart, as well as the item name of the item being added to the cart. I assume I need to check the cart quantity in 1 function, then have it call 1 of 2 other functions based on how many items are in the cart. The 2nd function would charge the shipping based on the item name. I don't know if the code is wrong, and where I should put the 2 additional functions I am adding. It isn't working though. I am adding 2 ways I have tried below. Code: me.shipping = function(){ switch(me.quantity){ case '0': return 0; break; case '1': return oneItemInCart(); break; default: otherNumber; return moreThanOneItemInCart(); break; } function oneItemInCart(); { if(item.name) { if(item.name.match = "Cricut Cartridge") return 4.39 else if(item.name.match = "Glitter") return 5.00 else return quantity*0.00; } } function moreThanOneItemInCart(); { if(item.name) { if(item.name.match = "Cricut Cartridge") return item.quantity*3.00-3.00+4.39 if(item.name.match = "Glitter") return item.quantity*4.00-4.00+5.00 else return quantity*0.00; } } Code: me.shipping = function(){ if( parseInt(me.quantity,10)===0 ) return 0; else if( parseInt(me.quantity,10)===1) return oneItemInCart(); else if( parseInt(me.quantity,10) > 1) return moreThanOneItemInCart(); else return quantity*0.00; function oneItemInCart(); { if(item.name) { if(item.name.match = "Cricut Cartridge") return 4.39 else if(item.name.match = "Glitter") return 5.00 else return quantity*0.00; } } function moreThanOneItemInCart(); { if(item.name) { if(item.name.match = "Cricut Cartridge") return item.quantity*3.00-3.00+4.39 if(item.name.match = "Glitter") return item.quantity*4.00-4.00+5.00 else return quantity*0.00; } } Here is the original document - the part I edited is the me.shipping part http://simplecartjs.com/ If I create a cookie in PHP here. PHP Code: setcookie('cookie_cl_'.$client_id, 'cookie_cl_'.$client_id, $time, "/","", 0); the php script is set on domain B the javascript I want to read the cookie is set on domain B as well However, the hosted on DOMAIN A Code: <script src=domain B .js> I want the cookie to remain on domain B, but if I open the JS file using domain A, both php and JS are using domain B, though I can't seem to get the JS to find the cookie, is it looking at domain A ? am I suppose to set a domain on cookie for this to work? Hopefully this makes sense. Hello, I know there are dozens of threads on this topic but I can't figure out how to do what I want to do. I have three variables I want to store in a cookie when a user leaves this page which is a college project: http://jimbolgs.agilityhoster.com/wo.../ClockUTC.html They are (from the linked JS file): extraMins, geoLoc, UTCHours. I would also like to retrieve them on return to the page. Any help appreciated, Thanks. |