I'm writing a kind of shopping cart in JS and I have a small problem. When I click on 'buy' in my html, the product has to show up on another page. My listeners work but I have a problem. My array is always empty and the shopping cart shows that the array also is empty. I think the problem is in the addProducts() function. Can somebody please help me? Thanks in advance.
Code:var products = new Array(); // create new array document.addEventListener("load", addButton, false); document.addEventListener("DOMContentLoaded", showProducts, false); document.addEventListener("DOMContentLoaded", loadPage, false); //connects html button to listener function addButton(event) { var button = document.getElementById("sell"); button.addEventListener("click", add_item, false); } function loadPage(){ getCookie(); } function getCookie(){ var elements = document.cookie.split('='); var products_cookie = elements[1].split('%'); for(var i=0;i < products_cookie.length-1;i++) { var tmp = products_cookie[i].split('$'); addProduct(tmp[0], tmp[1], tmp[2]); } } function setCookie(){ var date = new Date(); date.setTime(date.getTime()+(2592000)); //expire time = 30 days var expires = "; expires="+date.toGMTString() var text = ""; for (var i = 0; i < products.length; i++){ text+= products[i][0] + "$" + products[i][1] + "$" + products[i][2] +"%"; // saves naam $ aantal $ prijs } document.cookie = "tradepoint"+text+expires; } // adds item when button is clicked function add_item(){ addProduct("Movie", 2, 1); } function addProduct(pName, pAmount, pPrice){ var product = new Array(pName, parseInt(pAmount), pPrice); // products[products.length] = product; setCookie(); } function showProducts(){ if (products.length != 0){ document.getElementById("shopList").innerHTML = "<ul><li>Full</li></ul>"; } else{ document.getElementById("shopList").innerHTML = "<ul><li>Empty</li></ul>"; } }


Reply With Quote

Bookmarks