Obmerk Kronen
Obmerk Kronen

Reputation: 15979

Jquery cookie always return 1

Using the jquery cookie plugin I have a very simple function as so :

demoPopupInit: function() {
        // alert($.cookie('modal-popup'));
       if (! $.cookie('modal-popup')) {
           $.cookie('modal-popup',1) ;
        }

        if ( $.cookie('modal-popup') <= 3 ) {
            // return;

        var modal_cookie = $.cookie('modal-popup') ;
        modal_cookie = modal_cookie++;
        $("#intro_index").modal({backdrop:true});
        $.cookie('modal-popup', modal_cookie );
        }

    },


    }

I am sure it is a very simple mistake, but my poor JS skills do not allow me to understand why the alert() in the begining always turn 1..

I also tried

   if (! $.cookie('modal-popup') == NULL) {
       $.cookie('modal-popup',1) ;

But of course ,the problem is not there , and no other error reported in console. My aim is to turn the modal pop-up on only on 3 first visits .

Upvotes: 1

Views: 126

Answers (2)

SSA
SSA

Reputation: 5483

Just change post increment to preincrement:

modal_cookie = modal_cookie++;

to

modal_cookie = ++modal_cookie;

Also cookie returns a string value, to be safe use parseInt to compare int value. and avoid reading cookie multiple times, save it in a varible.

Short:

demoPopupInit: function() {

       if (!$.cookie('modal-popup')) {
           $.cookie('modal-popup',1) ;
        }
        var curval = parseInt($.cookie('modal-popup'));
        if ( curval <= 3 ) {
            // return;

        $("#intro_index").modal({backdrop:true});
        $.cookie('modal-popup', ++curval);
        }

    },

Upvotes: 1

ggdx
ggdx

Reputation: 3045

Try:

if($.cookie('modal-popup').length < 1){ 
  $.cookie('modal-popup',1);
}

If the cookie doesn't exist, the length will be -1; if it does, it will be 1 or greater.

Upvotes: 1

Related Questions