How to add and manage id inside dynamically created rows of jquery table

I am having a problem with how to add an identifier for my string. I have this code to populate the body of a table using json data.

var table = ''; $.each(result, function (i, item) { table += '<tr class="test"><td>' + item.ip_address + '</td><td>' + item.app_name + '</td><td>' + item.crit_severity + '</td><td>' + item.user_password + '</td></tr>'; }); $("#tableLinks tbody").html(table); 

and i have this table

 <table class="table table-bordered" id="tableLinks" style="width:70%;margin"> <thead> <tr> <th>IP ADDRESS</th> <th>APPLICATION NAME</th> <th>CRIT/SEVERITY</th> <th>USERNAME/PASSWORD</th> </tr> </thead> <tbody> </tbody> </table> 

I use this code for testing, but it does not work. What could be a mistake here? Thanks

 $(".test").on('click', function() { alert('test'); }); 
+5
source share
1 answer

What you are currently using is called a β€œdirect” binding, which will only attach to the element that exists on the page when your code makes an event binding call.

You need to use Event Delegation using the .on () approach with delegated events when creating elements using a dynamic or manipulation selector (for example, deleting and adding classes).

General syntax

 $(staticParentSelector).on('event','selector',callback_function) 

Example

 $("#tableLinks tbody").on('click', ".test", function(){ alert('test'); }); 

Instead of document you should use the nearest static container.

Delegated events have the advantage that they can handle events from descendant elements that will be added to the document later. By selecting the element that is guaranteed to be present during the attachment of the delegated event handler, we can use delegated events to bind the click event to dynamically created elements, and also to avoid the need for frequent attachment and removal of event handlers.

 $(function() { $("#tableLinks tbody").on('click', ".test", function() { snippet.log('test'); }); var result = [{ ip_address : 123456, app_name:'test', crit_severity: 'crit_severity', user_password: 'user_password' }]; var table = ''; $.each(result, function(i, item) { table += '<tr class="test"><td>' + item.ip_address + '</td><td>' + item.app_name + '</td><td>' + item.crit_severity + '</td><td>' + item.user_password + '</td></tr>'; }); $("#tableLinks tbody").html(table); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script> <table class="table table-bordered" id="tableLinks" style="width:70%;margin"> <thead> <tr> <th>IP ADDRESS</th> <th>APPLICATION NAME</th> <th>CRIT/SEVERITY</th> <th>USERNAME/PASSWORD</th> </tr> </thead> <tbody> </tbody> </table> 
+7
source

Source: https://habr.com/ru/post/1237228/


All Articles