How to add Click event for Dynamically Created Button Using jQuery


We can add event to dynamically created element using on() method. The on() method used to attach event handler to selected elements.

on() Method
$(document).ready(function(){
  $("body").on("click",".add-row",function(){
    //code here...
  });
});

Example

The following example shows, how to add click event for dynamically created button using jQuery.

 
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>   
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Add</th>
          <th>Remove</th>
        </tr>
      </thead>
      <tbody id='table-body'>
        <tr>
          <td><input type='text' name='name[]'></td>
          <td><input type='button' class='add-row' value='+'></td>
          <td><input type='button' class='remove-row' value='-'></td>
        </tr>
      </tbody>
    </table>
    <script>
      $(document).ready(function(){
        $("body").on("click",".add-row",function(){
          $("#table-body").append("<tr><td><input type='text' name='name[]'></td> <td><input type='button' class='add-row' value='+'></td><td><input type='button' class='remove-row' value='-'></td></tr>");
        });
        $("body").on("click",".remove-row",function(){
          $(this).parents("tr").remove();
        });
      });
    </script>
  </body>
</html>
Try it Yourself

Demo