1

I have the following code in html:

<table class="table table-striped">
<thead class="inner">
    <tr>
        <th>Name</th>
        <th>Parent</th>
        <th>Priority</th>
        <th>Action</th>
    </tr>
</thead>
<tbody id="check">
    <tr>
        <td><a href="">test</a></td>
        <td>null</td>
        <td>0</td>
        <td>
            <button value="3" type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
    <tr>
        <td><a href="">Lifestyle</a></td>
        <td>null</td>
        <td>1</td>
        <td>
            <button value="2" type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
    <tr>
        <td><a href="">Travel</a></td>
        <td>null</td>
        <td>1</td>
        <td>
            <button value="1" type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
</tbody>

And I have the following code in the footer:

$("#check tr td button").click(function () {
    alert('here');
});

But the event does not seems to work. Why is my code not working? The data in table are created after a ajax call. Is it because of ajax?

3 Answers3

2

Remember at the time you bind event, maybe at that time the object $("#check tr td button") is not exist in DOM!

So, the solution is bind event after ajax done.

Put your code into success method of ajax

$.ajax({
 url: 'url',
 data: [],
 success: function() {
   // render table code
   // bind event here
   $("#check tr td button").click(function () {
    alert('here');
   });
 }
});

OR you can use the event click of document.

  $(document).on("click", "#check tr td button", function() {
    // do something you want here 
  });
ThinhCoder
  • 466
  • 4
  • 8
0

The event is registered before the elements exist in the DOM, which is why the function is not triggered. The solution is to define the code after your ajax or use event delegation as below

$(document).ready(function() {
  $(document).on("click", "#check tr td button", function() {
    alert('here');
  });
});
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
0

Try this:

$(document).on("click", "#check tr td button", function() {
    alert('here');
});

OR

 $(document).ready(function() {
  $(document).on("click", "#check tr td button", function() {
    alert('here');
  });
});
Ramki
  • 452
  • 2
  • 16