1

I am using jQuery sortable and have two two lists that I am moving items from one to another. The first move works just fine with a double click. Now that it is in the second list, I want to allow users to remove items by clicking and hitting the delete key. My plan to do this is to have a click event trigger and decorate the list item with a class, and then when the delete key is hit, it will delete all items with that class. At this point, I am having issues getting the click event to take hold. Since I am creating the list items dynamic, I am using the on event keyword. My html for the second list looks like this:

<div id="CartContents" class="ui-widget-content">
     <ul id="sortableArea" class="cartSortable">
     </ul>
</div>

My js for trying to handle the click event looks like this:

$('.cartSortable li').on("click", function () {
    alert('here');
    $(this).toggleClass("selected");
});

The alert is there so that I know if it was hit. Let me know what you think is wrong or where my understanding is lacking.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nate
  • 761
  • 1
  • 8
  • 27

2 Answers2

2

Since you are creating the list items dynamically, you need to delegate the event:

$('.cartSortable').on('click', 'li', function () {

Or, if your script is executed before the <body>:

$(document).on('click', '.cartSortable li', function () {
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • This worked. Thanks. My quick understanding from reading the link you provided is that the event is binded to the div that exist on page load with a reference to the the li that will be created later. Is this correct, or is there a better way to think about it? – Nate Nov 17 '15 at 15:36
  • You've got the right idea. The event is *delegated* to `.cartSortable`, which looks for a child `li` that was clicked. jQuery also changes `this` to point to the clicked `li` inside the event handler. – Blazemonger Nov 17 '15 at 15:56
-1

you can use jQuery's live method which binds event handler to all elements that match current query selector. http://api.jquery.com/live/

$('.cartSortable li').live("click", function () {
    alert('here');
    $(this).toggleClass("selected");
});
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
  • 1
    Live has been deprecated and removed from modern JQuery versions. 4+ years ago and this would have been a valid answer. – epascarello Nov 17 '15 at 15:39