curtis
curtis

Reputation: 109

Using jQuery: remove, add and animate li in ul

I have an ajaxcheck box. When checked, it makes an AJAX request back to the server, gets the data and should modify the current ul.

$('#event_filters').change(function() {
//#$('spinner').show();
   $.ajax({
      url: "/search/filters.json?search=13",
      success: function(data){
      $("#results").children('li').each(function(){
        $(this).text('blah');
      });
      alert('came here'+data);
      //how to modify current ul to remove old li's and add new ones
      },
   });
});

I've seen this feature on some other sites and I believe they add animate as well as the transition of removing old li's and adding new ones seems really smooth.

Upvotes: 1

Views: 4964

Answers (1)

Amith George
Amith George

Reputation: 5916

You will need to explain what you mean by old li's and new li's. Also, please show the contents of the variable data.

Assuming, by old li's you mean ALL existing li's, you can remove them using

$("#ulToRemoveFrom li").remove();

If you want to remove only some lis, maybe they have some class on them, or maybe some value or some other property. Checkout http://api.jquery.com/category/selectors/ to understand how to select the elements you want, and then call remove on them.

if you want to animate the removal, use one of the effects mentioned here http://api.jquery.com/category/effects/

sample: (http://api.jquery.com/animate/)

$("#ulToRemoveFrom li.offendingClass").animate({
        opacity: 0.25,
        left: '+=50',
        height: 'toggle'
    }, 5000, function () { $(this).remove();});

........

http://api.jquery.com/category/manipulation/ has many functions to add a new element to the dom.

assuming data is a json array ["text 1", "text 2", "text 3"], you could do the following ...

var items =  JSON.parse('["text 1", "text 2", "text 3"]');

var $ul = $("#ulToRemoveFrom");
$.each(items, function(index, item) {
    $ul.append('<li>' + item + '</li>');
});

Checkout http://jsfiddle.net/5kxbr/2/ ... Play around with it, or better still fork and modify it to suit your question ...

Upvotes: 5

Related Questions