1

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

1
  • You have multiple elements with the same id. That is not valid HTML and you should fix it so that you can safely select elements by id. Commented Jun 26, 2013 at 2:50

1 Answer 1

3

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');
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thank-you so much for that concise explanation. One more question. How would I get the id of each <a> in the rows generated? I tried var id = ($this).id; without success.
I juts tried........ var id = $(this).attr('id'); an I can get the ID of each clicked <a> tag. Thanks Arun you were a great help.
@user2522307 you can simple say var id = this.id where this is the clicked element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.