5

i'm having a problem about how can i add an identifier for my row. I have this code to populate the table body 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 to test but it doesn't work. What could be the error here? Thanks

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

1 Answers1

7

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).

General Syntax

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

Example

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

In place of document you should use closest static container.

The 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, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove 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.github.io/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>
Satpal
  • 126,885
  • 12
  • 146
  • 163