javascript - How to edit and update values in a dynamic table using JQuery? - Stack Overflow

Below is code for adding inputs into a dynamic table and for each row an edit button is also generated,

Below is code for adding inputs into a dynamic table and for each row an edit button is also generated, my question is how would I pass the values in the table back into the input fields when I click on the edit button of a specific row and then update the specific row based on the changes made to the values in the input fields when i click on the update row button.

$("#btnAdd").on('click', function() {
  let row = '<tr> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
  $('tbody').append(row);

  $('td:contains("edit")').html("<button type='button'>" + "edit" + "</button>").on('click', function() {

  });
});
<script src=".3.1/jquery.min.js"></script>

<form>
  <div>
    <label for="insert-name">Name:</label>
    <input type="text" id="insert-name">
  </div>
  <div>
    <label for="insert-surname">Surname:</label>
    <input type="text" id="insert-surname">
  </div>
</form>

<button type="button" id="btnAdd">Add to Table</button>
<button type="button" id="btnUpdate">Update row</button>

<table>
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Surname</th>
      <th scope="col">Edit</th>
    </tr>
  </thead>
  <tbody id="tbody"></tbody>
</table>

Below is code for adding inputs into a dynamic table and for each row an edit button is also generated, my question is how would I pass the values in the table back into the input fields when I click on the edit button of a specific row and then update the specific row based on the changes made to the values in the input fields when i click on the update row button.

$("#btnAdd").on('click', function() {
  let row = '<tr> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
  $('tbody').append(row);

  $('td:contains("edit")').html("<button type='button'>" + "edit" + "</button>").on('click', function() {

  });
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <div>
    <label for="insert-name">Name:</label>
    <input type="text" id="insert-name">
  </div>
  <div>
    <label for="insert-surname">Surname:</label>
    <input type="text" id="insert-surname">
  </div>
</form>

<button type="button" id="btnAdd">Add to Table</button>
<button type="button" id="btnUpdate">Update row</button>

<table>
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Surname</th>
      <th scope="col">Edit</th>
    </tr>
  </thead>
  <tbody id="tbody"></tbody>
</table>

Share Improve this question edited Mar 8, 2020 at 14:25 Vassilis asked Mar 8, 2020 at 14:04 VassilisVassilis 8286 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Check this (Read JS ments)

$("#btnAdd").on('click', function() {
    let row = '<tr> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
    $('tbody').append(row);

    $('td:contains("edit")').html("<button type='button' class='edit'>" + "edit" + "</button>").on('click', function() {

		});
});

//--------------------------------------------------------//

$(document).on("click",".edit",function(){ // Click function on class '.edit' (your appended button)
    var name = $(this).parents("tr").find("td:eq(0)").html(); // Search for 'name' depending on this edit button parent.
    var surname = $(this).parents("tr").find("td:eq(1)").html(); // Search for 'surname' depending on this edit button parent.
    var rowNumber = $(this).parents("tr").index() // Get index of this edit button parent 'row'.
    $("#edit-name").val(name); // Read the name and put it  in '#edit-name' inside '.editArea'.
    $("#edit-surname").val(surname); // Read the surname and put it  in '#edit-surname' inside '.editArea'.
    $(".saveEdits").attr("for",rowNumber); // Store this row index as attribute in '.saveEdits' button to be able to pass it to the other function that saves data.
    $(".editArea").fadeIn(300); // Show the edit box.
});

$(".saveEdits").click(function(){ // Function to save data
  var rowNumber = parseInt($(this).attr("for")); // Get the row number that we already define in the prev. function.
    $('td:eq(0)','tr:eq('+(rowNumber+1)+')').html($("#edit-name").val()); // Update 'td' content depending on the 'tr' index.
    $('td:eq(1)','tr:eq('+(rowNumber+1)+')').html($("#edit-surname").val()); // Update 'td' content depending on the 'tr' index.
});

$(".cancel").click(function(){ // Button to cancel edit.
  $("#edit-name").val(""); // Empty value.
  $("#edit-surname").val(""); // Empty value.
  $(".saveEdits").attr("for","0"); // Set row number to zero.
  $(".editArea").fadeOut(300); // Hide edit area.
});
.editArea{
  display:none;
  background:#fff;
  padding:10px;
  border:1px solid #ddd;
  border-radius:5px;
  box-shadow:0 0 0 #000;
  width:50%;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form>
      <div>
        <label for="insert-name">Name:</label>
        <input type="text" id="insert-name">
      </div>
      <div>
        <label for="insert-surname">Surname:</label>
        <input type="text" id="insert-surname">
      </div>
    </form>

    <button type="button" id="btnAdd">
      Add to Table
    </button>


    <table>
      <thead>
        <tr>
          <th scope="col">Name</th>
          <th scope="col">Surname</th>
          <th scope="col">Edit</th>
        </tr>
      </thead>
      <tbody id="tbody">

      </tbody>
    </table>
    
    <div class='editArea'>
      <label>Name</label>
      <input type="text" id="edit-name">
      <br>
      <label>Surname</label>
      <input type="text" id="edit-surname">
      
      <hr>
      <button class='saveEdits' for="0">Save edits</button>
      <button class='cancel'>Cancel</button>
    </div>
    
  </body>
</html>

Here is a solution with edit row in just within existent inputs

var counter = 0;
var current_row = null;
$("#btnAdd").on('click', function() {
  if (current_row == null) {
  if ( $("#insert-surname").val().length && $("#insert-name").val().length ) {
    let row = '<tr data-row="'+counter+'"> <td>' + $("#insert-name").val() + '</td> <td>' + $("#insert-surname").val() + '</td> <td>' + "edit" + '</td> </tr>'
    $('tbody').append(row);
    counter++;
    }
  } else {
    var select_row = $('tr[data-row='+current_row+']');
    let cells = $(select_row).find('td');
    $(cells[0]).text($("#insert-name").val());
    $(cells[1]).text($("#insert-surname").val());
  }
  clear_input();

$('td:contains("edit")').html("<button type='button'>" + "edit" + "</button>").on('click', function() {
    let cells = $(this).parents('tr').find('td');
    $("#insert-name").val($(cells[0]).text());
    $("#insert-surname").val($(cells[1]).text());
    current_row = $(this).parents('tr').data('row');
  });
});

$('#btnCancel').on("click", () => clear_input());

function clear_input() {
    current_row = null;
    $("#insert-name").val('');
    $("#insert-surname").val('');
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <div>
    <label for="insert-name">Name:</label>
    <input type="text" id="insert-name">
  </div>
  <div>
    <label for="insert-surname">Surname:</label>
    <input type="text" id="insert-surname">
  </div>
</form>

<button type="button" id="btnAdd">Add to Table</button>
<button type="button" id="btnCancel">Cancel</button>

<table id='data-table'>
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Surname</th>
      <th scope="col">Edit</th>
    </tr>
  </thead>
  <tbody id="tbody"></tbody>
</table>

Now let's begin with what wrong with the OP's solution. OP is trying to add event listner to an element which hasn't been created yet. The way we listen to dynamic data is through event delegation.

So for this:

<tbody>
  // dynamic <tr></tr>
</tbody>

We would attach our listener to some parent of it (not necessarily the closest parent) i.e., <tbody> in this case which is part of the dom when we run our js code.

I'm sure that there are various ways of doing it, but I gave it a shot by sticking close to your actual solution. Check it out:

function addToTable() {
    // insertion into row 
    let name = $("#insert-name").val();
    let surname = $("#insert-surname").val();
    let row = `<tr>
    	        <td>${name}</td>
                <td>${surname}</td>
                <td><button>Edit</button></td>
              </tr>`;
    $('#tbody').append(row);

    // clearing input fields
    $("#insert-name").val("");
    $("#insert-surname").val("");
}

function editTable() {
    let name = $("#insert-name").val();
    let surname = $("#insert-surname").val();
    
    // looking for tr with "active" class
    let row = $("#tbody tr.active");
    let rowArr = row[0].children;
    rowArr[0].innerHTML = name;
    rowArr[1].innerHTML = surname;
    row[0].classList.remove("active");

    // clearing input fields
    $("#insert-name").val("");
    $("#insert-surname").val("");
}

$("#btnAdd").on('click', function() {
    let isEdit = $("#btnAdd").hasClass("edit");
    if (isEdit) {
        editTable();
    } else {
        addToTable();
    }
    // remove class "edit"
    $("tbody").removeClass("edit");
});

// Adding event listner to the parent (event delegation)
$("#tbody").on('click', function(e) {
    $("#btnAdd").addClass("edit");

    // pass table data to input fields
    let row = e.target.closest("tr");
    row.classList.add("active");
    let rowArr = row.children;
    $("#insert-name").val(rowArr[0].innerHTML);
    $("#insert-surname").val(rowArr[1].innerHTML);
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form>
      <div>
        <label for="insert-name">Name:</label>
        <input type="text" id="insert-name">
      </div>
      <div>
        <label for="insert-surname">Surname:</label>
        <input type="text" id="insert-surname">
      </div>
    </form>
    <button type="button" id="btnAdd">
    Add to Table
    </button>
    <table>
      <thead>
        <tr>
          <th scope="col">Name</th>
          <th scope="col">Surname</th>
          <th scope="col">Edit</th>
        </tr>
      </thead>
      <tbody id="tbody">
      </tbody>
    </table>
    <script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </body>
</html>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745233146a4617768.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信