Editing, updating and canceling of table cell text not working using jQuery

You need to use delegated event handlers as you’re dynamically creating and removing the buttons.

In addition your logic is not quite right. You need to update the data attributes on the tr when the ‘update’ button is clicked, not the ‘cancel’.

The logic can also be improved by caching your selectors in variables instead of recreating them for each method call. In addition you can use closest() instead of parents() to get the nearest parent tr element, data() instead of attr() to read data attributes and also children() instead of find() to get the child td.

With that said, try this:

$(document).on('click', '.btn-edit', function(e) {
  let $tr = $(this).hide().closest('tr');
  $tr.children("td:eq(0)").html(`<input name="edit_name" value="${$tr.data('name')}">`);
  $tr.children("td:eq(1)").html(`<input name="edit_email" value="${$tr.data('email')}">`);
  $tr.children("td:eq(2)").prepend("<button class='btn btn-info btn-xs btn-update'>Update</button><button class='btn btn-warning btn-xs btn-cancel'>Cancel</button>")

$(document).on('click', '.btn-update', function(e) {
  let $tr = $(this).closest('tr');
  let name = $tr.find('[name="edit_name"]').val();
  let email = $tr.find('[name="edit_email"]').val();
  $tr.data({ name, email });
  $tr.find(".btn-update, .btn-cancel").remove();

$(document).on('click', '.btn-cancel', function(e) {
  let $tr = $(this).closest('tr');
  $tr.find(".btn-update, .btn-cancel").remove();
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<div class="container">
  <table class="table table-bordered ">
      <th width="200px">Action</th>
      <tr data-name='marzouk najib' data-email='[email protected]'>
        <td>marzouk najib</td>
        <td>[email protected]</td>
        <td><button class='btn btn-info btn-xs btn-edit'>Edit</button></td>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top