bmcswee
bmcswee

Reputation: 107

jQuery.data undefined outside the function it is created in?

I'm trying to store some data using jQuery.data in one function and access in another, but outside the first function, the data comes up undefined. Take a look at the code:

$("input:radio[name=gender]:checked").each(function()
{
    var genderChosen = $(this).val();
    alert(genderChosen);
    var gender = $(".gender");
    jQuery.data(gender, 'genderChosen', genderChosen);
    alert(jQuery.data(gender, 'genderChosen'));
    // Displays "male" or "female" depending on what's selected
});

var gender = $(".gender");
alert(jQuery.data(gender, 'genderChosen'));
// Displays "undefined"

Can someone please help me to retrieve this data outside the original function? I thought that was the whole point of the jQuery.data method...

Thanks!

Upvotes: 0

Views: 114

Answers (1)

vinczemarton
vinczemarton

Reputation: 8156

You should set it like this:

$('.gender').data('genderChosen', genderChosen);

You should get it like this:

var genderChosen = $('.gender').data('genderChosen');

And you are right. You should be able to access the attached data from anywhere.

And yes. In theory jQuery.data() does the same as .data() when you are attaching data to DOM elements. I'm not sure why it doesn't work for you, maybe there are browser specific quirks around this.

Upvotes: 1

Related Questions