Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript doesn't work on elements added by jquery's load(), prepend(), or append() functions

I have a comment system where a user submits a comment, the comment is processed, then the HTML for the comment is returned. jquery then adds that retrieved HTML to the comment system. that whole system works, but the comment buttons that requir javascript do not work unless I refresh the page. How do make my javascript work on elements added through load, prepend, or append?

Not sure if my question is clear, but here's the javascript I have:

$(function () {
  $(".replyform").submit( function (event) {
    event.preventDefault();
    id = $(this).attr("id").split('_')[1];
    text = $('textarea#text_'+id).val();
    $.post( "/api/add/comment/", {_csrf: _csrf, id: id, text: text, a: a},
      function (data) {
        $('#commentreplies_'+id).prepend(data);
        $('#replyform_' + id).hide();
    });
  });
});

I then have elements such as "reply" for each comment that have functions in an external javascript that do not work unless I refresh the page. Hopefully that made sense.

like image 200
Jonathan Ong Avatar asked Feb 22 '23 09:02

Jonathan Ong


1 Answers

Use jQuery live() (it is deprecated, see on()) function

like image 64
madhead - StandWithUkraine Avatar answered Apr 09 '23 15:04

madhead - StandWithUkraine