local storage - push() not working in javascript -
problem : uncaught typeerror: object #<object> has no method 'push'
in console.
code in http://jsfiddle.net
change storage item id(cart) , try again, looks stored item under "cart" id not json array @dc5 suggested in comment section
upd: try http://jsfiddle.net/vjkbq/4/
html
<div id='cart'></div> <input type="button" id="add" value="add cart item 1" /> <input type="button" id="add2" value="add cart item 2" />
javascript
//todo: move globals var storagename = 'mycart'; $(document).ready(function () { var item = { departmentid :333, categoryid:117, brandid:19, brandimage:" ", brandname:"general", id:711 }; var item2 = { departmentid :123, categoryid:321, brandid:18, brandimage:" ", brandname:"common", id:712 }; localstorage.clear(storagename); $('#add').click(function(){ addtocart(item); }); $('#add2').click(function(){ addtocart(item2); }); }); function addtocart(item){ //by @slebetman var items = json.parse(localstorage.getitem(storagename)); if (! (items instanceof array) ) { items = []; } var itemindex = getitemindexbyid(items, item.id); if(typeof(itemindex) === 'number'){ items[itemindex].quantity++; } else{ item.quantity = 1; items.push(item); } localstorage.setitem(storagename, json.stringify(items)); console.log(localstorage.getitem(storagename)); } //find search item index function getitemindexbyid(items, id){ for(var = 0; < items.length; i++){ if(items[i].id == id){ return i; } } return false; }
Comments
Post a Comment