Reputation: 13487
I have a todo list app which allows users to create todos. Right now I am building functionality using jquery which would allow users to delete tasks.
The problem is when I click the delete button on one todo the app ask me to confirm deletion on every list item. When I click "cancel delete" on one, it cancels on all of them. In other words, I am receiving duplicative behavior on all HTML elements.
I believe this is because all todo items are being generated from the same html.erb template, and in the template I give each element its ID so I can refer to it, but since every ID is the same, I can't differentiate between different todo's which contain elements with the same ID. How do I select a specific instance of an html element in Jquery?
Full JS Code/HTML output: http://jsfiddle.net/LvKED/
Rails html.erb code:
<%= form_for task do |form| %>
<li>
<% if !task.completed %>
<p> <%= task.title%></p>
<p>– <%=task.body %></p>
<%= form.check_box :completed, class: "completed_checkbox" %>
<%= button_to "Delete post",{}, class:"delete_button" %>
<%= link_to "Confirm deletion",{}, class: "confirm_links", id: "confirm_delete" %>
<%= link_to "Cancel",{}, class: "confirm_links cancel_delete" %>
</li>
<% end %>
<% end %>
Upvotes: 0
Views: 285
Reputation: 4824
in the event handler you can get reference to that particular item by this line of code:
var targetElement = $(event.target).closest('li');
Upvotes: 2
Reputation: 24638
Here is how you'll be able to manipulate the buttons and links:
$("#task").on("click",".delete_button",function(){
$(this).hide();
$(this.form).next('.confirm_links').show()
.next('.confirm_links').show();
return false;
});
$("#task").on("click",".cancel_delete",function(){
$(this).hide()
.prev(".confirm_links").hide()
.prev('form').find(".delete_button").show();
return false;
});
Button/link Demo: http://jsfiddle.net/fiddleyetu/LvKED/5/
The demo just shows one way of targeting one element out of many that may share the same selector. Other useful jQuery features you could use are:
jQuery.closest()
jQuery.nextUntil()
jQuery.prevUntil()
Find the one that works best for you.
Upvotes: 0
Reputation: 555
Ishita's answer seems to be correct but I don't have the reputation to comment on his answer yet. I think you have to wrap the "event.target" in a $() so it would be:
var targetElement = $(event.target).closest('li');
Hope that helps.
Upvotes: 2