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?

2
  • 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. Commented Aug 10, 2016 at 13:08
  • You should use the .on() function instead of .click() as .click() doesn't work for dynamic elements. Commented Aug 10, 2016 at 13:08

3 Answers 3

0

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

 $(document).on('click', 'button[id^="change_"]', function() {
        console.log("+++");
      });
Sign up to request clarification or add additional context in comments.

Comments

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("+++");
});

Comments

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')
  });
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.