How to update indexes of a listing dynamically

3

I have a table where I can select the number of items in an order. And in each row I have a number of 01 to 15 sequential where it identifies the quantity of items.

The problem is that when I delete an item, the interesting thing is that the numbers that identify each line update automatically and become random. Do you understand? Note: The list is made in table.

<table id="table_itens" class="table table-striped">
   <thead>
   <tbody>
      <tr id="exc_01">
          <td>01</td><!-- Estes números que eu quero atualizar dinamicamente -->
      </tr>
      <tr id="exc_02">
          <td>02</td><!-- Estes números que eu quero atualizar dinamicamente -->
      </tr>
      <tr id="exc_03">
          <td>03</td><!-- Estes números que eu quero atualizar dinamicamente -->
      </tr>
   </tbody>
</table>

JavaScript code:

<script type="text/javascript" language="javascript">
function adicionaItemPedido(){ 

  var contador = (cont < 10) ? '0'+ cont++ : cont++;

  $("#table_itens").append(
     '<tr id="exc_'+ contador +'">\n\
         <td><b>'+ contador +'</b></td>\n\
            <td>'+ referencia_estofado[0] +'</td>\n\
               <td><input type="hidden" class="id_est_revest_aux" value="'+ $("#revestimento_aux").val() +'" />'+ revestimento[0] +'</td>\n\
               <td><input type="hidden" class="id_padrao_aux" value="'+ $("#cod_padrao option:selected").val() +'" />'+ $("#cod_padrao option:selected").text() +'</td>\n\
               <td>'+ (($("#revestimento_aux_2").val() === 'undefined') ? "-" : $("#revestimento_aux_2").val()) +'</td>\n\
               <td>'+ (($("#cod_padrao_2").val() === 'undefined')       ? "-" : $("#cod_padrao_2").val()) +'</td>\n\
               <td>'+ referencia_estofado[1] +'</td>\n\
               <td>'+ $("#quantidade").val() +'</td>\n\
               <td>'+ $("#valor_unitario").val() +'</td>\n\
               <td>'+ $("#desconto_acrescimo").val() +'</td>\n\
               <td>'+ $("#valor_total").val() +'</td>\n\
               <td><button type="button" class="btn btn-danger btn-xs btnRemover"><i class="glyphicon glyphicon-remove" ></i> Remover</button></td>\n\
     </tr>'); 
}   
</script>
    
asked by anonymous 31.12.2014 / 12:08

1 answer

2

Firstly, when adding an element check how many are already there:

function adicionaItemPedido(){ 
  cont = $("#table_itens tr").length + 1;
  ...

Then, when the user clicks a remove button, update every line after the line being removed, and at the end remove the line itself:

$(document).on("click", ".btnRemover", function() {
  var linha = $(this).closest("tr"); // Acha a linha a ser removida

  // Recupera seu número (para atualizar os demais itens)
  var numero = parseInt(linha.attr("id").split("_")[1], 10);

  // Para cada irmão depois dessa linha...
  linha.nextAll().each(function() {
    // ...atualiza o id
    this.id = "exc_" + (numero < 10 ? "0" + numero : numero);
    // ...e o número exibido na tela
    $(this).find("td:eq(0) b").text(numero < 10 ? "0" + numero : numero);
    numero++;
  });

  linha.remove(); // remove a linha
});

(note that I used .on so that the remove button code applies to all buttons with If you are using a jQuery version prior to 1.7, you will need to replace them with% with%,% with% or something else.)

Complete example:

var referencia_estofado = [1,2];
var revestimento = [1];

function adicionaItemPedido(){ 
  cont = $("#table_itens tr").length + 1;

  var contador = (cont < 10) ? '0'+ cont++ : cont++;

  $("#table_itens").append(
     '<tr id="exc_'+ contador +'">\n\
         <td><b>'+ contador +'</b></td>\n\
            <td>'+ referencia_estofado[0] +'</td>\n\
               <td><input type="hidden" class="id_est_revest_aux" value="'+ $("#revestimento_aux").val() +'" />'+ revestimento[0] +'</td>\n\
               <td><input type="hidden" class="id_padrao_aux" value="'+ $("#cod_padrao option:selected").val() +'" />'+ $("#cod_padrao option:selected").text() +'</td>\n\
               <td>'+ (($("#revestimento_aux_2").val() === 'undefined') ? "-" : $("#revestimento_aux_2").val()) +'</td>\n\
               <td>'+ (($("#cod_padrao_2").val() === 'undefined')       ? "-" : $("#cod_padrao_2").val()) +'</td>\n\
               <td>'+ referencia_estofado[1] +'</td>\n\
               <td>'+ $("#quantidade").val() +'</td>\n\
               <td>'+ $("#valor_unitario").val() +'</td>\n\
               <td>'+ $("#desconto_acrescimo").val() +'</td>\n\
               <td>'+ $("#valor_total").val() +'</td>\n\
               <td><button type="button" class="btn btn-danger btn-xs btnRemover"><i class="glyphicon glyphicon-remove" ></i> Remover</button></td>\n\
     </tr>'); 
}   

$(document).on("click", ".btnRemover", function() {
  var linha = $(this).closest("tr"); // Acha a linha a ser removida
  
  // Recupera seu número (para atualizar os demais itens)
  var numero = parseInt(linha.attr("id").split("_")[1], 10);
  
  // Para cada irmão depois dessa linha...
  linha.nextAll().each(function() {
    // ...atualiza o id
    this.id = "exc_" + (numero < 10 ? "0" + numero : numero);
    // ...e o número exibido na tela
    $(this).find("td:eq(0) b").text(numero < 10 ? "0" + numero : numero);
    numero++;
  });

  linha.remove(); // remove a linha
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="table_itens" class="table table-striped">
   <thead>
   <tbody>
      <tr id="exc_01">
          <td>01</td><!-- Estes números que eu quero atualizar dinamicamente -->
      </tr>
      <tr id="exc_02">
          <td>02</td><!-- Estes números que eu quero atualizar dinamicamente -->
      </tr>
      <tr id="exc_03">
          <td>03</td><!-- Estes números que eu quero atualizar dinamicamente -->
      </tr>
   </tbody>
</table>
<button onclick="adicionaItemPedido()">Adicionar</button>

P.S. In terms of User Experience (UX), I would recommend taking care of some details:

  • If the user clicks the remove button twice by accident, he may end up removing two lines ... It might be interesting to block the use of the remove button for a second (accompanied by a visual indication, of course ), to avoid this possibility.

  • If two lines are the same or very similar, the user may find that the removal did not work (because the index stays constant after the update) and click remove again, frustrating for losing an item that still wanted.

    For this reason, I personally usually do not remove the item from fact but simply mark it as removed . This is done by wrapping the element in a live ( example ) tag or perhaps via CSS ( delegate ). That way, if the user regrets he can still restore it, at least while he has not yet submitted the data to the server.

  • 31.12.2014 / 12:39