Skip to content Skip to sidebar Skip to footer

Incrementing Cookie Value By 1 Via Javascript

I have below code for Reading and Setting Cookie taken from w3schhols.com. I have problem while incrementing the value of Cookie function isNumber (o) { return ! isNaN (o-0) &a

Solution 1:

Its a string, you need to cast it first:

var totalcart = parseInt(getCookie("totalcart"));

Solution 2:

Because when you retrieve the value from the cookie it is a string, this means when you add the 1 to the end it acts as a string. You need to use parseInt function to convert your string to an int, so you can run your equation.

functionaddToCart() {
var totalcart = parseInt(getCookie("totalcart"));
if (totalcart != null && totalcart != "" && isNumber(totalcart)) {
    totalcart += 1;
    setCookie('totalcart',totalcart, 2);
    jQuery('#totalcart').text(totalcart);
} else {
    setCookie('totalcart', 1 , 2);
    jQuery('#totalcart').text('1');
}
} 

Post a Comment for "Incrementing Cookie Value By 1 Via Javascript"