Page 1 of 1

jQuery - saving/using cookies

Posted: Wed Aug 17, 2011 9:35 am
by sipher_z
Hi

I am currently developing a shopping cart solution and I have a field, which is used for tax.

What I'm looking to do, is when the user selects the checkbox field for tax, then this is stored in the cookie, so when they go to other pages and then return to the cart, then these fields are checked.

I am using http://plugins.jquery.com/project/Cookie to achieve this.

I can create the cookie for the checkboxes, but I am struggling to then check the cookie and if it was for a checkbox, then set the checkbox as 'checked'.
I also need, the deletion of cookies. When the user unchecks the box, to the call something like $.cookie("vat_1", null)

I have the following code so far:

Code: Select all

                $(document).ready( function() {

                    $('input:checkbox[name="<?php echo $prod; ?>"]').click(function() {
                        var name = $(this).attr("name");
                        var value = $(this).val();
                        var date = new Date();
                        date.setTime(date.getTime() + (30 * 60 * 1000));

                        $.cookie(name, value, { expires: date });//Set the expires time as per your requirement.
                        cookie = $.cookie(name);

                        alert(cookie);
                    });

                });

All help is muchly appreciated.

Thanks

Re: jQuery - saving/using cookies

Posted: Wed Aug 17, 2011 9:55 am
by sipher_z
Ok, figured it out:

Code: Select all

                $(document).ready( function() {
                    if($.cookie("<?php echo $prod ?>"))
                    {
                       $('input:checkbox[name="<?php echo $prod; ?>"]').attr('checked',true)

                    }
                        $('input:checkbox[name="<?php echo $prod; ?>"]').click(function() {
                            var name = $(this).attr("name");
                            var value = $(this).val();
                            var date = new Date();
                            date.setTime(date.getTime() + (30 * 60 * 1000));

                            if ($('input:checkbox[name="<?php echo $prod; ?>"]').is(':checked'))
                            {
                                $.cookie(name, value, { expires: date });
                            }
                            else
                            {
                                    $.cookie(name, null);
                            }
                        });
                });