Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

jQuery.data() returns 'undefined' when retrieving data from dynamic elements

My case is very simple, I just tried to store data into an element which appended in the DOM dynamically. My problem is, whenever I tried to retrieve the data through the immediate appended object, the value is returning fine, but through the object returned from the click event through on function it is returning undefined. I searched about this earlier, but people in stackoverflow were just suggested about removing the camel casing etc. That did not help me out in my case. Any suggestions or fix will be more helpful.

My code:

$(document).ready(function(){

    xElement = $('<li class="test">click this (because this contains data)</li>').appendTo('ul');

    jQuery.data(xElement,"val","value1");

    alert(jQuery.data(xElement,'val'));

    $(document).on('click','ul li',function(){ alert(jQuery.data($(this),'val')); });
     });

A Fiddle :

Here

Upvotes: 3

Views: 1956

Answers (3)

Jon
Jon

Reputation: 23

Thank you DevlshOne, this was starting to cause me a bit of a headache - I cant vote you up or comment as I dont have enough reputation.

But if anyone is working with datatables this solves the problem of any hidden values (as the default table only shows 1- 10 ) and you can not access the data attr from 11 + as they get dynamically generated afterwards.

old code

$('.userId').on('click', function(){ var userId = $(this).data('id');

new code

$(document).on('click', 'td', function(){ var userId = $(this).data('id');

Thanks

Upvotes: 0

DevlshOne
DevlshOne

Reputation: 8457

$(document).ready(function(){
    xElement = $('<li class="test">click this (because this contains data)</li>').appendTo('ul');
    xElement.data("val","value1");
    //retrieving data from immediate object
    alert(xElement.data('val'));
    $(document).on('click','ul li',function(){ 
        //retrieving data through object from 'on'
        alert($(this).data('val')); 
    });
});

Very strange, but if you do it this way, it seems to work fine.

FIDDLEMETHIS

Upvotes: 1

SLaks
SLaks

Reputation: 887413

jQuery.data() takes a raw DOM element, not a jQuery object.

You need to either pass this directly, or call the instance method ($(this).data())

Upvotes: 4

Related Questions