I'm loading a table with DataTables. In each row I create a button to click, and the value automatically insert into an input in the opener windows. The function I use is this:
$("button").click(function() {
var id = $(this).val();
window.opener.document.getElementById('cliente-nombre').value = id;
window.parent.close();
});
The function is not working with the buttons loaded in the datatable. If I create a button which loads with the page (not when the page is fully loaded) it works without problem.
I suppose this doesn't work because they are created when the page is fully loaded.
When dealing with elements loaded in after page load, delegate the event handler via on() to a parent element to ensure they respond to the click.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
Here I use the document
object:
$(document).on('click', 'button', function() {
var id = $(this).val();
window.opener.document.getElementById('cliente-nombre').value = id;
window.parent.close();
});