1

A simple example of what I am trying to achieve:

$('.test-link').click(function(e) {
  e.preventDefault();
  alert($(this).attr('href'));
});
$('.test-form').submit(function(e) {
  e.preventDefault();
  $(this).append('<a href="testing" class="test-link">Click here</a>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="test-form">
  <input type="submit">
</form>

When the form is submitted it successfully creates the link with the class "test-link" which has a function ready to handle the click. When clicked I need to trigger the existing function, in this exemple it should alert "testing", but the link works as a regular link.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    And since you're not binding the newly created element properly, the click event bubbles up the DOM and triggers the submit event. – j08691 Oct 23 '18 at 20:19
  • 2
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Heretic Monkey Oct 23 '18 at 20:20

1 Answers1

1

Consider using jQuery's .on() method to ensure that your event logic is bound to elements that are added to the DOM in the future.

For example, you could change your code like this:

$(function() {

$('.test-form').submit(function(e) {
  e.preventDefault();
  $(this).append('<a href="testing" class="test-link">Click here</a>');
});
  
$('body').on('click', '.test-link', function(e) {

  e.preventDefault();
  alert($(this).attr('href'));
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form class="test-form">
  <input type="submit">
</form>

This means that your click handler will be called for any matching elements that currently exist, or that are added later on (ie after your form submit).

For more information, see the documentation for on(). Hope this helps!

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • Thanks! It worked! I am actually using $(document).on('click', '.async-interface-link', function(e) @Heretic Monkey also pointed to this other question: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Fabio Rizzo Sciubba Oct 23 '18 at 20:34
  • @FabioRizzoSciubba you're welcome - as a note, if the `.on()` can be called closer to `.test-link` (ie from `$('.test-form').on( .. )`) it is usually best practice and performs better - if this answer has helped in any way please consider accepting! :-) – Dacre Denny Oct 23 '18 at 21:01