I want to be able to append items to an unordered list (wibble) when an item is selected from a larger list (user_checkboxes). If a user clicks on an item in the ‘wibble’ list I would like to remove that item from the list.
The problem I am having is that the list items ‘a’ and ‘b’ work as I was hoping. i.e if i click on the list item they are removed from the list. Unfortunately any items that are added to the list by append don’t behave the same way. i.e They don’t get selected and removed from the list.
<ul class = "wibble">
<li>a</li>
<li>b</li>
</ul>
$(document).ready(function () {
$(".user_checkboxes").change(function() {
if ($(this).attr("checked")) {
$('.wibble').append('<li>'+newListItem+'</li>');
}
}
$('.wibble li').click(function() {
$(this).remove();
);
}
When you bind the
clickevent handler, the list elements don’t exist yet, so jQuery cannot bind any handlers to them.Use
.delegate()[docs] instead:This binds an event handler to
.wibble(which does exist) and listens to any click that originates from a descendantlielement.