Reputation: 470
I have have a a function that when a checkbox is checked i dynamically write out an li into a ol that is empty.
Code:
$(":checkbox").click(function() {
var checkedState = $(this).is(':checked');
if (checkedState == true) {
var productName = $(this).attr("title");
$("#selectedProductsList").append("<li class=\"productList " + this + "\"><p class=\"removeIcon\"><img src=\"images/remove-icon.png\" alt=\"Remove Product\" /></p><span class=\"productName\">"+ productName +"</span></li>");
};
});
Then when that writes out there is a remove icon that will remove the item from the ol when clicked. This remove icon has a class of removeIcon which can be seen in the dynamic li above.
I have a function that processes the remove call and then does some actions: Code:
$('.removeIcon').click(function() {
alert("starting");
});
Right now i have the remove action just trying to alert a message that it got called. But it seems that it is not getting into the function.
Is there a certain way that i need to access these dynamic li's other then the .click method? I saw this post: Dynamically Inserted DOM Elements are not Clickable using $.click()
Where they added .live vs .click but this doesn't seem to work either.
Any ideas?
Upvotes: 3
Views: 1106
Reputation: 5509
If got a idea, why dont u put you button in a object? here a little example(NOT TESTED its for helping you on a idea, but should work)
$(":checkbox").click(function() {
var checkedState = $(this).is(':checked');
if (checkedState == true) {
var productName = $(this).attr("title");
var product = $('<li class="productList"><span class="productName">'+ productName +'</span></li>"'); // create a object off the product
var removeButton = $('<p class="removeIcon"><img src="images/remove-icon.png" alt="Remove Product" /></p>'); // create a object off the image aswell
// now i can add a event to the object 'removeButton', in the same way what u did earlier(like $('.removeIcon'))
removeButton.bind('click', function() {
alert("This click function works");
});
// now add the remove button in front off the <span class="productName">
// im using prepend because that function adds HTML in front off the object
// append adds HTML at the end.
product.prepend(removeButton);
// put the product in your HTML
$("#selectedProductsList").append(product);
};
});
Upvotes: 0
Reputation: 322562
Use .delegate()
instead of live()
.
$('#selectedProductsList').delegate('.removeIcon','click',function() {
alert("starting");
});
It would be extremely wasteful to use .live()
since it appears that the elements you're targeting are all in the same container.
Upvotes: 1
Reputation: 338326
You need to use live()
for dynamically added elements ($(":checkbox").live('click', ...)
), because click()
will only run once and will only catch elements that exist up to this point.
Upvotes: 1
Reputation: 9234
try using the live event...
$(".removeIcon").live("click", function () {
alert("starting");
}
Upvotes: 2