Here is a jsFiddle to explain my problem. If you try to click on the button “Add an ingredient”, the button click event is called. My problem is that when I click on the “Create a subtitle”, it dynamically created “Add an ingredient” button for each sub-categories. All button have the same id beginning with “create-ingredient” concatenated with a unique ID so it creates a unique ID for the button.
I then use a “start with” selector in jQuery to select all button that start with “create-ingredient”. It just doesn’t select the ones that are dynamically created, it just work with the one that was originally in the html page.
Here is the click event not firing up on the dynamic ones:
$("[name^='create-ingredient']").click(function() {
alert('ingredient clicked');
return false;
});
What do I need to change so the dynamically created button event gets called?
Thanks!
clickwires up the event statically. You wanton, which triggers the event even on added elements.Note that the syntax for
onis slightly different thanclick. You typically use:where “container” selects a static container element (can just be “document”), and “selector” is the element you want to target.
Forked Fiddle.
Edit
Clarifying the above per David’s comment: the use of
onactually attaches an event handler to “container”, and delegates the callback to any elements inside the container that match “selector”. This is a case where it’s well worth reading the JQuery docs: