user7388204
user7388204

Reputation: 57

.data() is returning undefined

This is my code:

$.getJSON("link here", function (result) {
    $.each(result, function (i, value) {
        $('.usersOfGroupList').append($("<li id='userElement' data-userId='' ></li>").data('userIdFromGroups', value.Id).html(value.FirstName + " " + value.LastName));
        console.log($(".usersOfGroupList").data());
    });
});

The value in the data-method is storing the data correctly but when I try to log this value in my console I get the whole javascript-object when I just want the value of D. I've also tried with the key like this:

console.log($(".usersOfGroupList").data("userIdFromGroups"));

but that just gives me an

undefined-error

Upvotes: 1

Views: 352

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

id needs to be unique per element so remove id attribute from li.

Since you are adding data attribute to newly created li so you need to use li as selector and :eq(index) to get the correct li each time.

Do like below:-

console.log($(".usersOfGroupList li:eq("+i+")").data('userIdFromGroups'));

Sample hardcoded snippet:-

result = [{'Id':1,'FirstName':'A','LastName':'B'},{'Id':2,'FirstName':'C','LastName':'D'}];


$.each(result, function (i, value) {
  $('.usersOfGroupList').append($("<li data-userId='' ></li>").data('userIdFromGroups', value.Id).html(value.FirstName + " " + value.LastName));
  console.log($(".usersOfGroupList li:eq("+i+")").data('userIdFromGroups'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="usersOfGroupList">

So full code needs to be:-

$.getJSON("link here", function (result) {
    $.each(result, function (i, value) {
        $('.usersOfGroupList').append($("<li data-userId='' ></li>").data('userIdFromGroups', value.Id).html(value.FirstName + " " + value.LastName));// remove repetitive id
        console.log($(".usersOfGroupList li:eq("+i+")").data('userIdFromGroups')); // use index i to get correct li data
    });
});

Upvotes: 3

fingeron
fingeron

Reputation: 1182

It seems like you're giving the data to a newly created <li> under .usersOfGroupList, so you'll have to use the following to properly obtain it

$("#userElement").data("userIdFromGroups")

Also, in the above code it seems you're creating multiple elements with similar ids, which is very bad practice. Theoretically if there's only one <li>, it will work.

If it doesn't, that means you have some bad handling of asynchronous actions.

Since you're using an asynchronous function to obtain the data, and only then setting the data attributes on the desired elements. In the meantime, your code continues to run and tries retrieving the (yet unset) data property.

Upvotes: 0

Related Questions