0

I'm currently using jQuery cookie for a button

$('.vote').one('click', function(){      
    var cookieid = ($(this).data("id")); //cookie name
    alert ($.cookie(cookieid));  //..etc

This gives me a textbox saying "undefined". However, I do know that the variable cookieid is assigned, as alerting the variable gives me a value.

Furthermore, this script works fine if I use a 'cookieid' that I know I have assigned. For instance, I have a cookie named 17. When I alert ($.cookie('17')); everything works correctly.

I'm pretty sure the problem is not in my end of the code, so can jQuery cookie not handle variables?

Edit:

//creating cookie if none already exists
var cookieid = ($(this).data("id")); //cookie name
        if ($.cookie(cookieid) == 'active') //if cookie exists
        {
            //do nothing
        }
        else
        {
            $.cookie(cookieid, 'active');
        }

1 Answer 1

1

($(this).data("id")) returns a number.

alert(typeof $(this).data("id")); //number

Try converting it to a string:

alert ($.cookie(cookieid.toString())); 

Here's a working example: jsfiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, does converting the cookie to a string only necessary for alerts? I was just using an alert for the example, and maybe that's the only place it wasn't working. I've edited the post with additional info on how I'm using this.
this.data('id') returns a number if your data attribute value is a number, but it will return a string if the value was string. I guess this is why it wasn't working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.