How to add <li> dynamically in <ul> with jQuery?

Asked

Viewed 4,045 times

13

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

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>

As it stands it brings only the last item of Collection, I need to add the <li> dynamically.

3 answers

11


You probably have a <ul> on your page, set an ID for it or CLASS if you don’t. And success AJAX put the code below inside the for:

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

Or you can do it using each():

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>');
    })
}

7

It seems to me that you are always deleting the contents of #taskItem and filling it with the new value, so that you always have only the last presented by loop. Basically, the method of html() jQuery arrow the contents of a selector, regardless of what was previously on it. A solution would be to use the menu append(), adding elements at 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 of ID for class on the tag <a>. Can’t be too semantically correct.

6

Browser other questions tagged

You are not signed in. Login or sign up in order to post.