I’m using jquery .clone() to add HTML to my page according to user clicks.
I’d like to add onclick handlers to the newly created HTML. I know .on() can be used to trigger events on future-created HTML, but I believe that must be written (and executed) before the HTML is created.
In this example code, if the user selects “related_id” from the select list, jquery creates a field where the user can enter ids. I’d like to add an ajaxy thing here so the user can type the name of the related item instead of its id. The ajax request will depend on which field the user selected.
Generally speaking, I know how to make ajax requests with jquery, but how do I add the field-specific ajax code to my freshly created HTML?
Your jsfiddle has a whole lot of code in it, most of which is mostly irrelevant to this question. In any case, if I’m understanding you correctly, what you are seeking clarification on is fairly high-level anyway.
The first thing I would do is ensure you include a common
classin all of your new elements. Then, you will bind to the click event using.on()as follows:Note
#parentElementmust exist in the DOM before this click handler is created.Your
doAjaxRequestfunction will be something along the lines of the following:Note
.on()is available for this as of jQuery 1.7. For older versions see the following options:For version 1.4.4. the code would be as follows: