0

In my html I have the following ajax code which populate data into a table:

function generate_table() {

      var tr;
      $('#emp_body').html('');
      for (var i = 0; i < displayRecords.length; i++) {
        tr = $('<tr/>');
        tr.append("<td>" + displayRecords[i].id + "</td>");
        tr.append("<td>" + displayRecords[i].email_address + "</td>");
        tr.append("<td>" + displayRecords[i].mobile_number + "</td>");
        tr.append("<td>" + displayRecords[i].status + "</td>");
        tr.append("<td>" + displayRecords[i].credit_limit + "</td>");
        var $td = $('<td>').html('<a href="#" class="btn btn-info btn-md editbtn">Edit</a>');
        tr.append($td);
        $('#emp_body').append(tr);
      }
    }

I also have a jquery on click function:

jQuery('.editbtn').on('click', function() {

      var $row = jQuery(this).closest('tr');
      var $columns = $row.find('td');
      var values = [];

      jQuery.each($columns, function(i, item) {
          values.push(item.innerHTML)
      });
      console.log(values[0]);
      window.location.href = "/portal/admin/customerDetails?id=" + values[0];

    });

So the issue here is that, when I click on Edit button, it does not call the on click function. How can I fix this issue ?

kylas
  • 1,425
  • 6
  • 24
  • 38

1 Answers1

2

Your content is dynamicly added to the dom. Therefor it was not there yet when you added the click event handler so the handler was never attached to the button. You can use this code.

jQuery('#emp_body').on('click', '.editbtn', function(){});

from the jQuery docs:

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

Mark Baijens
  • 13,028
  • 11
  • 47
  • 73