user13834442
user13834442

Reputation:

how to dynamically change ids of row when one in the middle deleted

$(document).ready(function () {
            var counter = 0;

            $("#addrow").on("click", function () {
                var newRow = $("<tr>");
                var cols = "";

                cols += '<td><input type="text" class="form-control" name="PollOptionList['+counter+'].Title" /></td>';

                cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
                newRow.append(cols);
                $("table.order-list").append(newRow);
                counter++;
            });
            
            $("table.order-list").on("click", ".ibtnDel", function (event) {
                $(this).closest("tr").remove();
                counter -= 1
            });
        });

if the row with PollOptionList[1] in the middle deleted

<input type="text" class="form-control" name="PollOptionList[0].Title">
<input type="text" class="form-control" name="PollOptionList[1].Title">
<input type="text" class="form-control" name="PollOptionList[2].Title">

how to decrement all next rows ids, the result now is

<input type="text" class="form-control" name="PollOptionList[0].Title">
<input type="text" class="form-control" name="PollOptionList[2].Title">

after deletion i need

<input type="text" class="form-control" name="PollOptionList[0].Title">
<input type="text" class="form-control" name="PollOptionList[1].Title">

Upvotes: 0

Views: 216

Answers (1)

mplungjan
mplungjan

Reputation: 178126

Something like this

NOTE: I added a tbody

$(function() {
  const maxRows = 5;
  $("#addrow").on("click", function() {
    const counter = $("table.order-list tbody tr").length;
    $(this).prop("disabled",counter >= maxRows-1); // OR the one below
    /*
    if (counter >= maxRows) {
      alert("max "+maxRows);
      return;
    }
    */
    const newRow = $("<tr/>");
    const cols = `<td><input type="text" class="form-control" name="PollOptionList[${counter}].Title" /></td>
                  <td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>`
    newRow.append(cols);
    $("table.order-list tbody").append(newRow);
  });

  $("table.order-list").on("click", ".ibtnDel", function(event) {
    $(this).closest("tr").remove();
    $("table.order-list [name^=PollOptionList]").each(function(i, ele) {
      ele.name = `PollOptionList[${i}].Title`
    })
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="order-list">
  <tbody>
  </tbody>
</table>
<button id="addrow" type="button">Add</button>

Upvotes: 1

Related Questions