After dynamically creating html elements, is there anyway to fire an event?
-
23-06-2021 - |
Question
This is a goofy question, so sorry about that.
I'm creating html elements dynamically from an ASP.NET server control. After an element is created, or all of the elments are created, is there a way to force an event to fire on one of them? I understand that it's coming from the server to the client, but I'm looking for a way around that. Is there anything in the document that can listen for html being added or anything?
I'm creating the controls like this:
protected override void RenderContents(HtmlTextWriter output)
{
// htmlString is a dynamically built string of html
output.Write(htmlString);
}
The elements are a series of cascading drop-downs of which the user has the ability to save the selected value. So, if I select the value of the item when I create it, there's no way to kick off the event, which calls out to the database for data to fill its dependent control. There's a "no postbacks" rule here (not my rule).
Any help would be appreciated.
Solution
You can output javascript as part of the rendering and bind events to the dynamically created controls.
jQuery makes binding events very easy.
OTHER TIPS
If you want, fire a Function() from RegisterClientScriptBlock()
Example useage:
ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", false);
Or you can set up a live event on click etc on those new items.
$(document).on('click', '#exampleThing', function () {
// what you want to do
});