Nita Nita - 3 years ago 192
Javascript Question

jquery - bind function to button within xhr output

I output some information with xhr request. On this output I also have a button. I want to bind a function (send e-mail) to it, but for some reason I can't.

Obviously i have included jQuery and i do not get any errors in console. I tried few options already!

button html:

<button type="button" class="btn btn-primary sendraportemail" id="sendraportemail">SEND E-MAIL</button>


binding options i tried:

$(document).ready(function(){
$('#sendraportemail').click(function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);

});
});

(function() {
$('#sendraportemail').click(function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});
});

$('.sendraportemail').click(function(){
var uroemail = $('#uroemail').val();
console.log(uroemail);
});


I tried binding with $('#sendraportemail') or $('.sendraportemail'). What do i do wrong? Help highly appreciated.

Answer Source

You need to use delegated event binding which is necessary for capturing events on elements that are dynamically added after document.ready:

$(document).ready(function(){
  $(document).on('click', '#sendraportemail', function(){
    var uroemail = $('#uroemail').val(); 
    console.log(uroemail);  
  });            
});

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.

Source: https://api.jquery.com/on/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download