0

I have the below HTML and jquery snippet, the new rows are added correctly and the the rows are deleted when clicked on which is expected but for the .delete_row click it isn't calculated the row count correctly after a row is deleted.

So say I have added 3 custom rows, I click to delete one row, it will delete and a alert box will display, if I click to delete a second row the process will alert twice and when I click to delete the third row the alert will pop up 3 times.

A single alert should only ever display when one row is removed but it's like the delete a row is incrementing by one on each run, cant see why though!?

$("#add_row").on("click", function(e) {
  e.preventDefault();

  var row_num = $(this).data("id");
  var row_limit = 50;
  var code_snippet = '<div class="row"><dd>' + row_num + '</dd><dt><span class="delete_row" title="Delete Custom Row"><i class="fas fa-times"></i></span></dt></div>';

  if (row_num <= row_limit) {
    $("#count").val(row_num);

    $(code_snippet).insertBefore("#base");

    row_num += 1;

    $(this).data("id", row_num);
  }

  if (row_num >= row_limit) {
    // Disable button once limit reached
    $(this).attr("disabled", true).addClass("disabled");
  }

  $(".delete_row").on("click", function(e) {
    $(this).parent().parent(".row").remove();

    alert("Deleted Row");

    $("#add__row").data("id", ($("#add__row").data("id") - 1));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
  <dl>
    <div class="row row_header">Header Title</div>

    <div class="row align_right" id="base">
      <input type="hidden" name="count" id="count" value="0" />
      <button id="add_row" data-id="1">Add New Row</button>
    </div>
  </dl>
</fieldset>
mplungjan
  • 134,906
  • 25
  • 152
  • 209
llanato
  • 2,386
  • 6
  • 29
  • 54

0 Answers0