I have following code to implement simple practice shopping cart using JavaScript
. There is a checkout link which calls getcookie()
to check the value of the cookies stored. When nothing is in the cookie then click on the link alerts to make input. If non of the values are entered in the input box and hit "add to cart" then validation is done and error message is alerted.
For some reason, the cookie is not taking the value from the input field. I tried quite a while now but was not able to debug the code. Just an empty alert box is shown at last. I appreciate any debugging. Thanks in advance.
<script type="text/javascript">
var value;
var productID;
function setItem(abd) {
value = abd.value;
productID = abd.getAttribute("productID");
var intRegex = /^\d+$/;
var numberOfItems;
if (!intRegex.test(value) || (value <= 0)) {
alert('Please Enter valid numberofitem');
} else {
numberOfItems = value;
}
}
function getCookie() {
if (value == undefined) {
alert("There is nothing in the shopping cart!");
} else {
var cookieArray = document.cookie.split(';');
var printHolder = "";
for (var i = 0; i < cookieArray.length; ++i) {
var pairArray = cookieArray[i].split('=');
alert(pairArray[0]);
}
alert(printHolder);
}
}
function setCookie() {
if (value == undefined) {
alert("Please add number of items in text box");
} else {
document.cookie = productID + "=" + value + "; ";
alert(value + " Product(s) with id " + productID +
" has been added to shopping cart!");
}
}
</script>
<a href="javascript:getCookie()"> Checkout </a>
<input name="item-select" id="item-select"
productid="p001" style="width: 50px" onBlur="setItem(this)" >
<button type="button" onclick="setCookie()">Add to cart.</button>
The result I wanted is something like this at last!
This code works perfectly fine with some changes. I was using chrome and later found out that
Google Chrome doesn't create cookies when the file is on the
local machine
and loaded in browser directly using file path.
Rather try with localhost.
It is definitely working when you put the code in server. Chrome became pain in a b*t here!
If you were for idea on creating shopping cart with Javascript follow this link. http://www.smashingmagazine.com/2014/02/create-client-side-shopping-cart/