Dinamic refresh numbers after add input in jquery

Viewed 39

I need refresh number in correct order #1, #2, #3, #4.... after add input and reorder after remove anyone.

|add_input+| (button)

#1 |new_input| |remove| (button)

#2 |new_input| |remove| (button)

#3 |new_input| |remove| (button)

What i need? If i remove #2, the next number need be refreshed, so, #3 automaticaly change to #2, and if i add new input, he get #3

My code:

$(document).ready(function() {
  var i = 1;
  $('#add').click(function() {
    i++;
    $('#dynamic_field').append('<tr id="row' + i + '"><td>#' + i + '<input type="text" name="r[' + i + ']" placeholder="Insira o peso" class="form-control name_list" /></td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');
  });

  $(document).on('click', '.btn_remove', function() {
    var button_id = $(this).attr("id");
    $('#row' + button_id + '').remove();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="dynamic_field">
  <tr>
    <td>
      <button type="button" name="add" id="add" class="btn btn-success">Add</button>
    </td>
  </tr>
</table>

1 Answers

To achieve what you require you could create a function which updates the text in the cell when a row is added/removed. This number can also be derived from the row index instead of requiring a global variable, which should be avoided where possible.

In addition there's a few other things you can change to improve the code:

  • Remove the i global variable. You can use the index of the elements instead.
  • Remove the id attributes on content which can be appended to the DOM multiple times, as this will create invalid HTML. Use common class attributes instead.
  • Use DOM traversal to relate elements together when an event occurs.
  • Put a span in the tr which makes it much easier to target the location where the row number should be placed.

With all that said, try this:

$(document).ready(function() {
  let updateRowNumbers = () => {
    $('#dynamic_field tr td:nth-child(1) span').text(i => `#${i + 1}`);
  }

  $('#add').click(function() {
    $('#dynamic_field').append(`<tr class="row"><td><span></span> <input type="text" name="r[]" placeholder="Insira o peso" class="form-control name_list" /></td><td><button type="button" name="remove" class="btn btn-danger btn_remove">X</button></td></tr>`);
    updateRowNumbers();
  });

  $('#dynamic_field').on('click', '.btn_remove', function() {
    $(this).closest('.row').remove();
    updateRowNumbers();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="dynamic_field">
  <tr>
    <td>
      <button type="button" name="add" id="add" class="btn btn-success">Add</button>
    </td>
  </tr>
</table>

Related