4

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

4 Answers4

2

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

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
2

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) { ... });
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
1

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.....
 });
vikas devde
  • 11,691
  • 10
  • 35
  • 42
0

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.

This link may help you.

Community
  • 1
  • 1
Julien Fouilhé
  • 2,583
  • 3
  • 30
  • 56