Manipulate event with Jquery when form and link are generated automatically

Asked

Viewed 106 times

1

Jquery does not work when the form or a link is automatically generated. Example below:

This example works.

<a id='btnTreatInvite' class='btn btn-primary btn-sm fa fa-check' href='#'>&nbsp; Aceitar</a>  

$("#btnTreatInvite").on("click", function(e){
    e.preventDefault(); 
    alert('event works');       
}); 

When the same link is automatically generated does not work.

var table ='<table id="tableInviteRqd">';
    table +='<thead>';
    table +='<tr>';
    table +='<th data-toggle="true">Nome</th>';
    table +='<th data-hide="phone,tablet"></th>';
    table +='</tr>';
    table +='</thead>';
    table +='<tbody>';

$.each(data, function(i, item){ 
    table +='<td>' + item.name + '</td>';
    table += "<td><a id='btnTreatInvite' class='btn btn-primary btn-sm fa fa-check' href='teste.php'>&nbsp; Aceitar</a></td>";
 });                        
    table +='</tbody>';
    table +='</table>'; 
  • This is the stackoverflow in English. Translate your question.

1 answer

1

The problem is that you are associating the event with elements that do not exist in the DOM when it is read by the browser.

To resolve, you must make use of delegation, attaching the event to an element that exists on the page at the time it is loaded and delegating it to a particular element:

$("body").on("click", ".classeDosLinks", function(e){
    e.preventDefault(); 
    alert('event works');
}); 

Above the event attached to the body and delegated to elements with the CSS class classeDosLinks, even though you should wear a Scope shorter, i.e., attach the event to an element closer to the body, perhaps a <div/> which serves as a wrapper to dynamic content.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.