user3408779
user3408779

Reputation: 997

Displaying only one record from json object , using jquery each

Below is my code to display some notifications from json object.

$.each(valid_result, function(key, element){
      jQuery("#notifications_list").html('<a href="#"><i class="fa fa-users text-aqua"></i>'+element.notification+'</a>';
      console.log(key+' : '+element.notification);
     });

The above list will display here

<ul class="menu">
       <li id="notifications_list"></li>
  </ul>

But it is displaying only one record even though I have more records. Please suggest me where I am doing wrong. Any help would be greatly appreciated.

Upvotes: 0

Views: 241

Answers (2)

instead
instead

Reputation: 3471

You are overwriting results. Please use append() method instead of html().

jQuery.each(valid_result, function(key, element){
  jQuery("#notifications_list").append('<a href="#"><i class="fa fa-users text-aqua"></i>'+element.notification+'</a>');
  console.log(key+' : '+element.notification);
});

If there are many elements in Your JSON object, then better approach is to append only once like so:

var list = '';

jQuery.each(valid_result, function(key, element){
   list += '<a href="#"><i class="fa fa-users text-aqua"></i>'+element.notification+'</a>';
});

jQuery("#notifications_list").html(list);

Upvotes: 2

cli-ish
cli-ish

Reputation: 776

You are removing the old entry, you should append your code to it...

$.each(valid_result, function(key, element){
    $("#notifications_list").append('<a href="#"><i class="fa fa-users text-aqua"></i>'+element.notification+'</a>');
});

Upvotes: 1

Related Questions