Ad

JQuery Add/remove Items And Reset Counter

- 1 answer

I have the following piece of code:

var counter = $("#myTable tbody").children().length;

Remove function:

$(document).on('click', 'a.remove', function() {
    if(counter == 1) {
        return false;
    }

    $(this).closest('tr').fadeOut().remove();
    counter--;
});

Add Function:

$('#add').on('click', function() {
  if (counter > 10) {
      return false;
  }
  counter++;
  var newTr = $('<tr data-id="' + counter + '"></tr>');

  newTr.html(
      '<td><i class="icon reorder"></i></td>\
      <td><small>' + counter + '.</span></td>\
      <td> <input type = "text" name = "price[]" data-id = "' + counter + '"></td>\
      <td><a class="remove"><i class="icon delete"></i></a></td>\
      ');
  });

When removing item on click, I would like to reset counter, so the value between <small></small> is restored in sequence starting at 1.

Ad

Answer

Seems like you need, after remove an item, loop through all tr and setup small text and input data-id again with the new value

$(document).on('click', 'a.remove', function() {
    if(counter == 1) {
        return false;
    }

    $(this).closest('tr').fadeOut().remove();

    counter = 0;

    $("#myTable tbody").children().each(function(){
        counter++;
        $(this)
            .find("small").text( counter )
            .end()
            .find("input").attr( "data-id", counter );
    });
});
Ad
source: stackoverflow.com
Ad