How to add dynamically in ul with jQuery?

12

I'm bringing backend notifications and I need to dynamically add the path to them, how do I add a <li> to each response element?

JavaScript

$(document).ready(function () {
$.ajax({
    url: "/tasks/not-assign",
    dataType: "JSON",
    success: function (res) {
        for(var i = 0; i<res.length; i++) {
            $('#taskItem').html(res[i].title);
            var a = document.getElementById('taskItem'); //or grab it by tagname etc
            a.href = "/tasks/detail/" + res[i].id;
            }
        }
    });
});

HTML

<li>
      <a href="#" data-toggle="dropdown" role="button" aria-haspopup="true"
                   aria-expanded="false" style="color: #fff"><i class="fa fa-bell-o" aria-hidden="true"></i><span id="numberTask" class="badge"></span></a>
      <ul class="dropdown-menu">
             <li><a id="taskItem"></a></li>
      </ul>
</li>

The way it is, it only has the last item in the collection, so I need to add <li> dynamically.

    
asked by anonymous 20.09.2016 / 13:21

3 answers

11

You probably have a <ul> on your page, set an ID for it or a CLASS if you do not. And in%% of AJAX, put the code below inside success :

$('#id-do-ul').append('<li><a href="/tasks/detail/'+res[i].id'">'+res[i].title+'</a></li>');

Or you can do it using for :

var box = $('#id-do-ul');
success: function(res){
    $.each(res, function(i, v){
        box.append('<li><a href="/tasks/detail/'+i'">'+v.title+'</a></li>');
    })
}
    
20.09.2016 / 13:43
7

It seems to me that you are always deleting the contents of #taskItem and filling it with the new value, so you always have only the last one displayed by loop . Basically, jQuery's html() method directs the contents of a selector, regardless of what was previously there. One solution would be to use the append() method, which adds elements to the end of a list. Your code can be rewritten as

$.ajax({
  url: "/tasks/not-assign",
  dataType: "JSON",
  success: function (res) {
    for(var i = 0; i<res.length; i++) {
      var _li = "<li><a class='taskItem' href='/tasks/detail/" + res[i].id"'>" + res[i].title + "</li>";
      $(".dropdown-menu").append(_li);
    }
  }
});

Notice the change from ID to class in the <a> tag. It's never too much to be semantically correct.

    
20.09.2016 / 13:51
6

Use the .appendTo property

$('<li />', {html: "Meu texto", href: "/tasks/detail/"}).appendTo('ul.dropdown-menu')

Any questions follow the example: link

    
20.09.2016 / 13:50