javascript – Dynamically generated jQuery functions stop working when multiple instances-ThrowExceptions

Exception or error:

I have a chat application that works similar to hangouts. When you click on a user the chat div is generated. A simple feature I have is to allow them to press enter in a textarea to send the text, which works fine but if I have multiple dynamically generated jQuery functions only the LAST function will still work. I assume its stopping the previous instances from running. How do I fix this?

  • Again when the user starts a chat it loads the scripts for that chat session because I assume I need a unique ID rather than a class name so I could pass the ID to the database – probably not the most efficient way to do things I know:

    echo "$('#im-textbox".$receiver_id."').on('keyup', function(event){
    
     if (event.keyCode == 13) {
          //$(this.form).submit()
           var dataset = $('#im-form".$receiver_id."').serialize();
          $.ajax({
              url: 'data/add-chat.php',
              data: dataset,
              method: 'post',
              success: function(data) {
                  console.log(data);
              }
          });
    
          $('#im-textbox".$receiver_id."').val('')
         return false;
    
       }
      });
    ";
    

Thank you for your help!

How to solve:

I fixed it with this…

$(document).on('keyup', '#im-textbox".$receiver_id."', function(event){
  if (event.keyCode == 13) {
          //$(this.form).submit()
           var dataset = $('#im-form".$receiver_id."').serialize();
          $.ajax({
              url: 'https://easyrepair.us/manage/data/add-chat.php',
              data: dataset,
              method: 'post',
              success: function(data) {
                  console.log(data);
              }
          });

          $('#im-textbox".$receiver_id."').val('')
         return false;

       }
  });

Leave a Reply

Your email address will not be published. Required fields are marked *