Hunkeone
Hunkeone

Reputation: 505

Javascript push Object to cookies using JSON

Hi All on click button I need to add object to array and then write array to cookies. From the start this array can be not empty so I parse cookie first.

function addToBasket(){
        var basket = $.parseJSON($.cookie("basket"))

        if (basket.length==0||!basket){
            var basket=[];
            basket.push(
                { 'number' : this.getAttribute('number'),
                    'type' : this.getAttribute('product') }
            );
        }
        else{
            basket.push(
                { 'number' : this.getAttribute('number'),
                    'type' : this.getAttribute('product') }
            );
        }
        $.cookie("basket", JSON.stringify(basket));
    }

And HTML

<button type="button" class="btn btn-success btn-lg" number="12" product="accs" onclick="addToBasket()">Add</button>

Unfortunately I'm getting Uncaught ReferenceError: addToBasket is not defined onclick. Can't understand what am I doing wrong? Thanks!

Upvotes: 0

Views: 2413

Answers (1)

megawac
megawac

Reputation: 11353

I simplified your code a good deal, heres a fiddle: http://jsfiddle.net/yJ6gp/

I wired the click event using jQuery and simplified some of your code (see comments). Note I changed your html a little so I could select the add basket button by class - change as desired.

$(function () {//doc ready
    $.cookie.json = true; //Turn on automatic storage of JSON objects passed as the cookie value. Assumes JSON.stringify and JSON.parse:
    $('.add-basket').click(function() {
        var basket = $.cookie("basket") || []; //if not defined use an empty array
        var $this = $(this);

        basket.push({
            'number': $this.attr('number'),
            'type': $this.attr('product')
        });
        console.log(basket);
        $.cookie("basket", basket);
    });
});

Upvotes: 2

Related Questions