Reputation: 5449
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?
Upvotes: 0
Views: 178
Reputation: 18233
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 class
in all of your new elements. Then, you will bind to the click event using .on()
as follows:
$("#parentElement").on('click','.newClass', function() {
var me = $(this).text(); //gets the specific text from each .newClass element when clicked
doAjaxRequest( me );
}
Note #parentElement
must exist in the DOM before this click handler is created.
Your doAjaxRequest
function will be something along the lines of the following:
function doAjaxRequest( elemText ) {
$.ajax({
...
data: elemText,
...
});
}
Note .on()
is available for this as of jQuery 1.7. For older versions see the following options:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
For version 1.4.4. the code would be as follows:
$("#parentElement").delegate('.newClass', 'click', function() {
var me = $(this).text(); //gets the specific text from each .newClass element when clicked
doAjaxRequest( me );
}
Upvotes: 2
Reputation: 16959
Why don't you just bind the handler to the $clone
before you add it to the document?
$clone.on("change", function(){
//Do my AJAX
});
Upvotes: 1
Reputation: 7344
You can insert a <script type='text/javascript'> ... your jquery code here </script>
tag along with the rest of your HTML.
Upvotes: 1