0

I'm currently trying to use the .data() method to store data using a variable. However, for some reason it isn't working. Here is my proof of concept code:

var option = 'x';
$(this).data({ 'x' : 0 });
alert($(this).data(option));
$(this).data({ option : 20 });
alert($(this).data(option));

Surprisingly both of the alerts return 0 as opposed to 0 and then 20. Any help is really appreciated! Thanks!

1
  • 2
    Since this is answered, let me tell you a secret: User Chrome or Firefox developer tools and use console.log(...) instead of alert(...), it will save you a lot of time. Commented Sep 27, 2011 at 19:59

5 Answers 5

3

This is because in the second version, you are referencing the key "option" instead of the variable option (key "x").

var option = 'x';
$(this).data({ 'x' : 7 });
console.log($(this).data(option));
$(this).data({ option : 20 });
console.log($(this).data('option'));

A simpler version of this:

option = 'x';
console.log({option: 20});

Outputs:

Object { option=20 }

You can however use the key value syntax with a variable.

$(this).data(option, 20 );
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for clarifying. However, how can I set the data value of 'x' without explicitly using 'x'? Or how do I set the value of 'x' without using 'x'. Thanks!
2

You want to access the property... like this..

$(this).data({ option : 20 });
alert($(this).data('option'));

Comments

1

The problem is that your option keyword in your object literal is being interpreted as a literal string for the key, rather than x (this is just how object literals work). If you want to be able to use a variable key, you'll need to use a temporary object. E.g.,

var option = 'x';
$(this).data({ 'x' : 0 });
alert($(this).data(option));
// create a data object so you can use a variable for the key
var obj = {};
obj[option] = 20;
$(this).data(obj);
alert($(this).data(option));

Comments

0

The reason is that your second one

$(this).data({ option : 20 }); 

sets 20 to the option property, when you are actually meaning to set it to the x property.

I think this is what you are wanting to do instead:

var option = 'x'; 
$(this).data({ x : 0 }); 
alert($(this).data(option)); 
$(this).data({ x : 20 }); 
alert($(this).data(option)); 

Alternatively, you can instead use the key value syntax like this:

var option = 'x'; 
$(this).data(option, 0); 
alert($(this).data(option)); 
$(this).data(option, 20); 
alert($(this).data(option)); 

Comments

0

The key to the data object cannot be a variable.

What you can do is:

var option = 'x';
var data = {};
data['x'] = '0';
$(this).data(data);
alert($(this).data(option));

Comments

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.