Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of values with jquery each function

Tags:

html

jquery

ajax

I'm trying to get data value from an <li data-nid="1"> tag. The <li> list is generated from an Ajax query response.

$.each(data.notifications.detail,function(index, element){
$('#notifications_list').append('<li id="element" data-nid ='+element.id+'><a>'+element.texte+'</a></li>');
});

to recover value, I tried the following method :

var array = new Array();
  $( "#element").each(function() {
        var id = $( this ).data( "nid" );
        array.push(id);
   });

But i'm always getting just one element, and its always the first one. So maybe someone clarify me the situation.

like image 892
KubiRoazhon Avatar asked Sep 18 '25 09:09

KubiRoazhon


1 Answers

Firstly you cannot have multiple elements with the same id, hence the point of using an each() on an id selector is completely redundant. You should change the id to a class.

To create the array of values from the appended elements you can simply use map(). Try this:

$.each(data.notifications.detail, function(index, element){
    $('#notifications_list').append('<li class="element" data-nid="' + element.id + '"><a>' + element.texte + '</a></li>');
});

var array = $(".element").map(function() {
    return $(this).data("nid");
}).get();

Also note that you could create the array of values in the same each() loop as you append the new li elements, like this:

var array = [];
$.each(data.notifications.detail, function(index, element){
    array.push(element.id);
    $('#notifications_list').append('<li class="element" data-nid="' + element.id + '"><a>' + element.texte + '</a></li>');
});
like image 164
Rory McCrossan Avatar answered Sep 20 '25 02:09

Rory McCrossan