How to dynamically update a listing

Asked

Viewed 573 times

3

I have a table where I list the amount of items in an order. And in each row I have a number of 01 to 15 sequential where identifies the amount of items.

The problem is that when I delete an item, the interesting thing was that the numbers that identify each row update automatically and get 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>
  • What do you mean "get random"? If you had 1, 2, 3, 4 and removed the 2, it’s supposed to stay 1, 2, 3 (the 3 turn 2 and the 4 turn 3) or is it something else?

  • Hello @mgibsonbr is exactly that. Do you have any idea how to do this?

  • 1

    I avoidance do this, preferring to mark the deleted items with a <del></del> (i.e. showing them cut) and keeping the numbering, to simplify. But if that’s what you want, I know how to do yes, just a moment...

1 answer

2


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

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

Then, when the user clicks on 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 the .on so that the remove button code applies to all buttons with that class, current or future. If you are using a version of jQuery earlier than 1.7, you will need to replace them with live, delegate or something else.)

Full 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>
<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>
<button onclick="adicionaItemPedido()">Adicionar</button>

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

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

  2. If two lines are the same or very similar, the user may find that the removal did not work (because the index remains constant after the update) and click remove again, frustrated by losing an item that he still wanted.

    For this reason, I personally usually do not remove the item in fact but simply mark it as removed. This is done by wrapping the element in a tag <del> (example) or maybe via CSS (text-decoration:line-through;). This way, if the user regrets he can still restore it, at least while he has not submitted the data to the server.

  • Thank you very much worked perfectly thank you. vlws!

  • I was going to indicate this page in the FAQ, but I see you’ve figured out yourself hehe :)

  • Neh! hahahahaha

Browser other questions tagged

You are not signed in. Login or sign up in order to post.