Reputation: 771
I am building a To Do App and I am trying to delete an item without having to render a new page. Below is my code for the list of to-dos.
<ul id="unordered_list">
<div class="to_do_list">
<% @list.each_with_index do |list, i| %>
<li data-index="<%= i %>">
<%= link_to list.title, '#' %>
<ol id="list_items_<%= i %>" class="hidden"></ol>
<div delete-index="<%= i %>">
<%= link_to "Delete", to_do_list_url(list),
:method => :delete, :remote => true %>
</div>
</li>
<% end %>
</div>
</ul>
My question is how can I use AJAX to remove the item when I click on the delete button? I tried to do this with
$('#unordered_list').find('input:delete').on('ajax:success', function(event){
$(event.currentTarget).parent().remove();
})
Could anyone tell me what I did wrong? I think the way I tried to retrieve the jQuery object to be clicked and to be removed is wrong but I have not been able to find a solution elsewhere.
Your help is much appreciated!
Upvotes: 0
Views: 3341
Reputation: 7442
Few things:
Your selector for the delete link is wrong - you are searching for an input, while link_to generates an anchor tag.
Also, in the callback function you can use "this" to get the element that triggered the event (the link).
Additionally, just calling "parent" will get the closest parent, when in reality you want to delete the list item. You should use "closest", which traverses up the dom tree till it finds a matching element.
You can use do this instead:
$('#unordered_list li a').on('ajax:success', function(event){
$(this).closest('li').remove();
})
Upvotes: 3