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?