title: How to add an onclick method on dynamically created button using jquery
body: <p>I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating. </p>
  
  <pre><code>'&lt;button type="button" onclick="test()" id="btnHistory" class="btn btn-success"&gt;History&lt;/button&gt; '
  </code></pre>
  
  <p>but it leaves me an error saying the test function isn't defined. </p>
  
  <p><a href="https://i.stack.imgur.com/m3kiA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m3kiA.png" alt="enter image description here"></a></p>
  
  <p>here's my whole code: </p>
  
  <pre><code>$.ajax({
      type: "POST",   
      url: "../php_scripts/getUnits.php",
      success: function(data){
          var items = JSON.parse(data);
  
          /*var btnSomething = $("&lt;button&gt;")
          .attr('class', 'btn btn-danger')
          .attr('id', 'asdf')
          .html('Save');
  */
  
  
  //$('#content').append(btnSomething);
  
          for (var i = 0; i &lt; items.length; i++) {
  
              //test();
              $('#myTable').append('&lt;tr&gt;&lt;td&gt;' + items[i].unitId + '&lt;/td&gt;&lt;td&gt;'+
               items[i].pcName +'&lt;/td&gt;&lt;td&gt;'+ items[i].user + '&lt;/td&gt;&lt;td&gt;'+ 
               items[i].department+'&lt;/td&gt;&lt;td&gt;'+items[i].location+ '&lt;/td&gt;&lt;td&gt;'+ 
               items[i].dateAssigned + '&lt;/td&gt;&lt;td&gt;' + items[i].status +'&lt;/td&gt;&lt;td&gt;' +
               '&lt;button type="button" onclick="test()" id="btnHistory" class="btn btn-success"&gt;History&lt;/button&gt; ' + 
               '&lt;button id="btnUpdate" class="btn btn-primary"&gt;Update&lt;/button&gt; ' +
               '&lt;button id="btnDelete" class="btn btn-danger"&gt;Delete&lt;/button&gt; ' + 
               '&lt;/td&gt;&lt;/tr&gt;');
          }
  
          function test(){
              alert('test');
          }
  
          /*$(document).on("click", "#btnHistory", function(){
            alert ('History clicked ');
          });*/
  
      }
  });
  </code></pre>