[Answered ]-Add or Remove Row in Input Table Along With Some Available Jinja

1👍

You can first clone tr whenever Add row button is clicked then use find("input").val("") to empty value attribute and find("td:eq(0)").text(length) to add new i value to first td . Now , when remove is clicked then just use .closest('tr') this will get closest tr and remove that tr . Also, you need to adjust i value again inside your td so use .each loop to iterate through trs and change it.

Demo Code :

$(".add").on("click", function() {
  //get length of tr 
  var length = $(".my_dynamic_table tr").length + 1
  console.log(length)
  //clone first tr
  var cloned = $(".my_dynamic_table tr:first").clone();
  $(cloned).find("input").val(""); //empty values of all cloned inputs
  $(cloned).find("td:eq(0)").text(length); //add `i` value 
  $(cloned).appendTo($(".my_dynamic_table")) //append to tbody
})
//onclick of remove button
$(document).on("click", ".remove", function() {
  $(this).closest("tr").remove(); //remove tr
  //loop through tr
  $(".my_dynamic_table tr").each(function(i) {
    $(this).find("td:eq(0)").text((i + 1)) //change `i` value
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="" method="POST">
  <table class="table table-hover my-5">
    <thead class="">
      <tr>
        <th>No</th>
        <th>Name</th>
        <th>rank</th>
        <th>gmail</th>
        <th>Delete?</th>
      </tr>
    </thead>
    <tbody class="my_dynamic_table">
      <tr>
        <td>1</td>
        <td><input type="text" name="name" value="{{ i.name }}"></td>
        <td><input type="text" name="rank" value="{{ i.rank }}"></td>
        <td><input type="email" name="gmail" value="s@gmail.com"></td>
        <td><i class="fa fa-times-circle remove" style="font-size: 22px; color: red;">x</i></td>
      </tr>
    </tbody>
  </table>
  <div class="row mx-5">
    <button class="btn btn-warning add" type="button">Add row</button>
    <button type="Submit" class="btn btn-primary ml-auto">Submit</button>
  </div>
</form>
👤Swati

Leave a comment