0

I'm adding a new row into the table which is called people_table using the following code:

  $("#add_new_row").click(function() {
    console.log("***");
    $('table#people_table').append('<tr><td>Dima</td><td>Petrov</td><td>30</td><td><button type="button" class="btn btn-success" id="change_4">Change</button></td></tr>');

  });
...
<button type="button" class="btn btn-primary" id="add_new_row">Add new row</button>
<table class="table table-hover" id="people_table">
   <tr>
    <th>Name</th>
    <th>Surname</th>
    <th>Age</th>
    <th>Modify</th>
   </tr>
   {% for person in people %}
   <tr>
     <td>{{ person[1] }}</td>
     <td>{{ person[2] }}</td>
     <td>{{ person[3] }}</td>
     <td><button type="button" class="btn btn-success" id="change_{{ person[0] }}">Change</button></td>
   </tr>
   {% endfor%}
</table>

But after adding the row the following function

  $("button[id^='change_']").click(function() {
    console.log("+++");
  });

does not work for the button in the new added row, but it works for other buttons. What's the problem?

  • It does not work because the code ran BEFORE you added the button to the page. You either need to bind the event directly or use event delegation. – epascarello Aug 10 '16 at 13:08
  • You should use the .on() function instead of .click() as .click() doesn't work for dynamic elements. – Romy Mathews Aug 10 '16 at 13:08

3 Answers3

0

try this, use method on for dynamically added elements...

 $(document).on('click', 'button[id^="change_"]', function() {
        console.log("+++");
      });
Ivan Karaman
  • 1,224
  • 1
  • 7
  • 11
0

For newly added dom element .click() will not useful in that case you have to use .on('click' event listner.

$("button[id^='change_']").on('click',function() {
    console.log("+++");
});
Rahul Patel
  • 5,248
  • 2
  • 14
  • 26
0

Try this enter link description here

 $("#add_new_row").click(function() {
    console.log("***");
    $('table#people_table').append('<tr><td>Dima</td><td>Petrov</td><td>30</td><td><button type="button" class="btn btn-success" id="change_4">Change</button></td></tr>');
addNewRow();
  });

  function addNewRow()
  {
   $("button[id^='change_']").click(function() {
    alert('click')
  });
  }