0

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:

$(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);  
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary sendraportemail" id="sendraportemail">SEND E-MAIL</button>

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

2
  • the $(documen).ready()... is the correct one... no need to have the rest 2. Commented Oct 1, 2017 at 7:15
  • these are option i tried, didn't have them all 3 in the same time. And none of these are correct. See answer. Commented Oct 1, 2017 at 7:23

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. 1 comment. There is ) missing in line 5 of your code. Could you make a correction so i can accept you answer. Thank you very much connexo
There was no brace missing, but one too much. Corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.