user2522307
user2522307

Reputation: 11

get click event from dynamically created data in JQuery

The code below is generated dynamically using an Ajax call and placed in a hardcoded div called studentresults.

<div id="studentresults" class="row span8 offset2">
  <table id="tablestudent" class="table table-striped table-hover center-table">
    <thead>Heading for my table</thead<
      <tbody>
        <tr id="showstudents">
          <td>29041</td>
          <td>jan</td>
          <td>jan</td>
          <td>
            <a class="btn" href="#">View Results »</a>
          </td>
          <td id="29041">
            <a id="29041" class="btn showstudent" href="#">Delete Student » </a>
          </td>
        </tr>
        <tr id="showstudents">
           .... another dynamic record from Ajax...
        </tr>
     </tbody>
  </table>
</div>

That works fine. However I would like a another Ajax call on the Delete Student tag. I cannot understand how to write the jQuery click function for this dynamic content.

The JQuery call doesn't work

$('.showstudent').click(function(){

 alert('In click');

});

However this works in the hard coded div container

 $('#studentresults').click(function () {

 alert('In click');

});

How can I access the dynamic <a> content

Upvotes: 1

Views: 1303

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388436

In case of dynamic elements you need use event propagation based event listeners.

When you use $('.showstudent').click(..) to register an event handler, it executes the selector at the execution time and the dynamic elements may not be present at that time, thus the event handlers will not get attached to those elements

$(document).on('click','.showstudent', function(){
    alert('In click');
});

Upvotes: 3

Related Questions