jQuery: responding to click event of element added to document after page load
- by morpheous
I am writing a page which uses a lot of in situ editing and updating using jQuery for AJAX.
I have come accross a problem which can best be summarised by the workflow described below:
Clicking on 'element1' on the page results in a jQuery AJAX POST
Data is received in json format
The data received in json format
The received data is used to update an existing element 'results' in the page
The received data is actual an HTML form
I want jQuery to be responsible for POSTing the form when the form button is clicked
The problem arises at point 6 above. I have code in my main page which looks like this:
$(document).ready(function(){
$('img#inserted_form_btn').click(function(){
$.ajax({'type: 'POST', 'url': 'www.example.com', function($data){
$(data.id).html($data.frm);
}), 'dataType': 'json'}
});
});
However, the event is not being triggered. I think this is because when the document is first loaded, the img#inserted_form_btn element does not exist on the page (it is inserted into the DOM as the result of an element being clicked on the page (not shown in the code above - to keep the question short)
My question therefore is: how can I get jQuery to be able to respond to events occuring in elements that were added to the DOM AFTER the page has loaded?