Reputation: 65
I have post adding functionality, where posts can be added and you can comment on posts, problem is commenting works fine on existing posts, but when you add new post, and comment on that newly added post, it doesn't work. here is what I have http://jsfiddle.net/testtracker/Nh2NQ/
first check that comments works fine on existing posts, then add a post, now try to comment on that newly added post.. it doesn't work...whats the problem here. pls help
thanks
Upvotes: 4
Views: 81
Reputation: 11751
JQuery binds events to the elements when the page loads, so this is why when the event is not triggered on newly added elements as there is no event binded with them.
this will surely work under any circumstances
$('#posts').on('submit', '.comment_entry form', function(e) {
code to add comment.....
});
Upvotes: 1
Reputation: 129792
This only adds a listener to the elements that are found when the selector is evaluated:
$('.comment_entry form').submit( ...
Your new form does not exist at this point, and so no listener is registered.
Use a live delegate instead:
$('#posts').on('submit', '.comment_entry form', function(e) { ... });
Upvotes: 2
Reputation: 123367
try this : http://jsfiddle.net/Nh2NQ/5/
I changed this line
$('.comment_entry form').submit(function (e) {
});
into
$('body').on('submit', '.comment_entry form', function (e) {
...
});
so using event delegation you can attach your submit handler also to dynamically inserted form
elements. Feel free to change body
with some other common parent hierarchically "closer" to your elements
Upvotes: 2
Reputation: 2658
That's because jQuery initializes the submit event before your element exists. When you add the new .comment_entry form
, jQuery doesn't know it and the submit event is not bound to this specific element.
Upvotes: 0