0

In an app I'm working on, I'm trying to target a specific dynamically generated element in a list of dynamically generated elements (search results).

Each element has a button with a generated ID (primary key in the database).

I've tried using this article: How do I attach events to dynamic HTML elements with jQuery?, but it does not fit my situation.

HTML code:

<div id="search-result">
 //example of generated element
 <div>
  username(<user_id>)
  <button id="<user_id>">Uitnodigen</button>
 </div>
 //end of generated element
</div>

I have already managed to select the generated element using

Jquery:

$("#search-result").on("click", "button", function(event)  {
 user_id=event.target.id;
  $("#search-result").on("click", "button", function(event)  {
  user_id=event.target.id;
});

Yet when I want to call on the element, for instance using:

$("#search-result").find("user_id").html("Loading...");
//or
$("#search-result").on("click", "#user_id", function(event)  {
 //code
});

But both solutions don't work. The .find() function cannot find dynamically generated elements. The .on() function requires an event, yet the event has already been fired previously.

Would there be an alternative to .on() that does not require an event, or an alternative to .find that can find dynamically generated elements. Or perhaps a different solution?

1 Answers1

0

'user_id' would be a selector for HTML tag <user_id />. That’s why it worked with 'button': because it’s existing tag. To target it in jQuery, you should use '#user_id'.

Try the below:

$("#search-result").on("click", "#user_id", function(event)  {
    // magic happens here
});

I would suggest using class names to avoid potential repetition of id.

The Witness
  • 910
  • 7
  • 12
  • Thank you for pointing out that I forgot the #, The Witness. However, I forgot to add one piece of the code where I already use the .on method in order to determine which element has been clicked (it's added now). Because of this, I cannot add a second 'click' event. – Chris Wagenaar Aug 25 '19 at 09:28