jquery: reappend <tr>s to <tbody> after removing them

69 views Asked by At

I have to buttons: Add, there I want to add s to my (they come from a selected number) and Reset where want to remove those elements. I know I need to clone DOM elements after removing them, but how do I implement it. I´m relatively new to JS. Alternatively I can switch to a checkbox with this solution here: with checkbox and cloning Any help appreciated - thks.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>reprex jquery</title> 
    <meta charset="UTF-8">
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

    <script>
    $(document).ready(function() {
        // what´s the value of the integer input?
        var no = 10; 
        let i = 1;
        $("#btn-add").click(function() {
            while (i <= no) {
                $("#tbl tbody").append("<tr><td><input></input></td><td><textarea></textarea></td></tr>");
                $("#tbl input")[i-1].setAttribute("name", "s" + i);                
                $("#tbl input")[i-1].setAttribute("value", i);
                $("#tbl textarea")[i-1].setAttribute("name", "c" + i);  
                ++i;
            }   
        });
    });
 
    $(document).ready(function() { 
        $("#btn-remove").click(function() { 
            $("#tbl tr:gt(0)").remove();
        });
    });   
    </script>
 

</head>
<body>
    <div>
        <button class="btn" id="btn-add" type="button">Add</button>
        <button class="btn" id="btn-remove" type="button">Reset</button>
    </div>

    <table id="tbl">
        <thead>
            <tr>
                <th>col1</th>
                <th>col2</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</body>
</html>

1

There are 1 answers

1
Twisty On BEST ANSWER

You can add back your rows by checking the status of i. Since it's defined more globally, as you continue to use it, the value changes. Consider the following.

$(function() {
  var no = 10;
  var i = 1;
  
  $("#btn-add").click(function() {
    if (i > 1) {
      i = 1;
    }
    while (i <= no) {
      $("#tbl tbody").append("<tr><td><input></input></td><td><textarea></textarea></td></tr>");
      $("#tbl input")[i - 1].setAttribute("name", "s" + i);
      $("#tbl input")[i - 1].setAttribute("value", i);
      $("#tbl textarea")[i - 1].setAttribute("name", "c" + i);
      ++i;
    }
  });

  $("#btn-remove").click(function() {
    $("#tbl tbody tr").remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div>
  <button class="btn" id="btn-add" type="button">Add</button>
  <button class="btn" id="btn-remove" type="button">Reset</button>
</div>

<table id="tbl">
  <thead>
    <tr>
      <th>col1</th>
      <th>col2</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Here you can see that i is changed in your while. You may need to reset it when the User clicks on "Add" button.