Ad

JQuery Form Submit And Disable Cookie Issue

- 1 answer

I am working on a sample system that enabled Shopify customers to add samples to their cart only once, as a cookie remembers if a sample has been added to the cart. Once an item has been selected and added the ability to add again should be disabled.

However, it seems like the whole add process is disabled. What am I doing wrong?

Live view

$('#{{ product.handle }}').submit(function (additem) {
    $(this).find(':input[type=submit]').prop('disabled', true).val('Sample Added!');
    $.cookie('sample', '{{ product.handle }}', {
        expires: 7
    });
});

if ($.cookie('sample', 'balancing-treatment-sample')) {
    $('#balancing-treatment-sample-wrap').addClass("added");
    $('#balancing-treatment-sample-buy').prop('disabled', true).val('Sample Added!');
} else {}
if ($.cookie('sample', 'cleanser-mask-sample')) {
    $('#cleanser-mask-sample-wrap').addClass("added");
    $('#cleanser-mask-sample-buy').prop('disabled', true).val('Sample Added!');
} else {}
Ad

Answer

the library you have used is no lnger maintained now $.cookie

Use LocalStorage instead

The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().

localStorage.setItem('myCat', 'Tom');

The syntax for reading the localStorage item is as follows:

var cat = localStorage.getItem("myCat");

The syntax for removing the localStorage item is as follows:

localStorage.removeItem("myCat");

moreover, you need to store all added items in the cart and keep them disabled so you need a collection of an array but localStorage doesn't support them so you can convert them to JSON string with JSON.stringify() and then JSON.parse() them to reuse. Change your script to

$('#{{ product.handle }}').on('submit', function (additem) {
    $(this).find(':input[type=submit]').prop('disabled', true).val('Sample Added!');
    let CartNotEmpty = localStorage.getItem('sample') !== null;
    let itemsCart = CartNotEmpty ? JSON.parse(localStorage.getItem('sample')) : Array();
    itemsCart.push('#{{ product.handle }}');
    localStorage.setItem('sample', JSON.stringify(itemsCart));
});


let cart = JSON.parse(localStorage.getItem('sample'));


if ($.inArray('#balancing-treatment-sample', cart) !== -1) {
    $('#balancing-treatment-sample-wrap').addClass("added");
    $('#balancing-treatment-sample-buy').prop('disabled', true).val('Sample Added!');
}
if ($.inArray('#cleanser-mask-sample', cart) !== -1) {
    $('#cleanser-mask-sample-wrap').addClass("added");
    $('#cleanser-mask-sample-buy').prop('disabled', true).val('Sample Added!');
}
Ad
source: stackoverflow.com
Ad