How to add the amount of a product, if the product is repeated when it is added to an HTML table with JavaScript?

3

I have a table where I add products with quantity and price, and when a product is repeated, I must add the amount of the product that is in the table plus the quantity of the product that is being added. I have a code that does that to me, but only when the product that is in the first row is repeated.

So I urge you to help me so that when a product is repeated no matter what row it is in, if it is the first row or the last row adds me those amounts.

This is my code:

var cont = 0;
var total = 0;

function agregar() {

  var cantidad = $("#Cantidad").val();
  var IDInsumo = $("#idInsumo").val();
  var Precio_Compra = $("#Precio_Compra").val();
  var subtotal = Precio_Compra * cantidad;
  total = subtotal + total;
  console.info(total);
  $("#total").val(total);

  if (cont == 0) {
    cont++;
    fila = '<tr class="selected" id="fila' + cont + '" onclick="seleccionar(this.id)"><td>' + cont + '</td><td><input type="hidden" value="' + IDInsumo + '"><input type="hidden" value="' + cantidad + '"><input type="hidden" value="' + Precio_Compra + '">' + IDInsumo + '</td><td>' + cantidad + '</td><td>' + subtotal + '</td></tr>';
    $('#tbodydatos').append(fila);
    return;
  }

  var id = "";
  var cantidad1 = 0;
  var precio1 = 0;
  $("#tablaDatos tbody tr").each(function(i, e) {

    var tr = $(e);
    var td = $(e).find("td").eq(1);

    id = $(td).find("input").eq(0).val();
    cantidad1 = $(td).find("input").eq(1).val();
    precio1 = $(td).find("input").eq(2).val();



    var fila = "";

    if (id == IDInsumo) {
      var tcan = parseInt(cantidad) + parseInt(cantidad1);
      var tpre = parseFloat(precio1) + parseFloat(Precio_Compra);

      tr.remove();
      cont++;
      fila = '<tr class="selected" id="fila' + cont + '" onclick="seleccionar(this.id)"><td>' + cont + '</td><td><input type="hidden" value="' + IDInsumo + '"><input type="hidden" value="' + tcan + '"><input type="hidden" value="' + tpre + '">' + IDInsumo + '</td><td>' + tcan + '</td><td>' + tpre + '</td></tr>';
      $('#tbodydatos').append(fila);
      reordenar();
      return false;
    } else {
      cont++;
      fila = '<tr class="selected" id="fila' + cont + '" onclick="seleccionar(this.id)"><td>' + cont + '</td><td><input type="hidden" value="' + IDInsumo + '"><input type="hidden" value="' + cantidad + '"><input type="hidden" value="' + Precio_Compra + '">' + IDInsumo + '</td><td>' + cantidad + '</td><td>' + subtotal + '</td></tr>';
      $('#tbodydatos').append(fila);
      reordenar();
      return false;
    }
  })
}

function reordenar() {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" id="idInsumo" placeholder="Insumo" />
<input type="text" id="Cantidad" placeholder="Cantidad" />
<input type="text" id="Precio_Compra" placeholder="Precio de Compra" />
<button onclick="agregar()">Agregar fila</button>

<hr/>

<table id="tablaDatos" class="table table-bordered">
  <thead>
    <tr>
      <td>Numero del Insumo</td>
      <td>Insumo</td>
      <td>Cantidad</td>
      <td>Subtotal</td>
    </tr>
  </thead>
  <tbody id="tbodydatos"></tbody>
  <tfoot>
    <tr>
      <td colspan="3"></td>
      <td><input type="text" id="total" disabled /></td>
    </tr>
  </tfoot>
</table>
    
asked by Programador avanzado 26.05.2017 в 14:28
source

1 answer

1

The problem is in the each and the conditions that you put inside. What you do is the following:

  • For each row of the table:
  • If the ID matches:
  • Create a row with the summed values
  • Destroy the original row
  • Includes the new row in the table
  • Finish loop execution
  • If the ID does not match
  • Create a row with new values
  • Includes the new row in the table
  • Finish loop execution
  • Go to the next element
  • The problem is that even if you have the ID in the table, if it does not appear in the first row, the ID with which it is compared (the one in the first row in 1.1) will never match the one in input hidden, always going to go by the else (1.2), a new row will be created and the execution of the loop will stop (with the return false which would be 1.2.3) so it will never be reached to the row in which IDs match. (I hope you have explained me well)

    That you can solve it by not having a else and rearranging the code a bit. This way, you will make it not repeat ( DRY !) And it will be easier to maintain. This solution is based on the fact that, if a matching row has not been found, the behavior is similar to if there were no rows directly (without the reordenar() , which can be added to it).

    The idea would be the following:

  • Move the code that checks if there is only one element and adds a row at the end.
  • Add the reordenar to the code from step 1.
  • Remove else from inside the loop.
  • Add a variable that indicates whether a row has been found and the sum has occurred.
  • If no such match has occurred: execute the code from step 1.
  • The modified code (with comments to illustrate the changes above):

    var cont = 0;
    var total = 0;
    
    function agregar() {
    
      var cantidad = $("#Cantidad").val();
      var IDInsumo = $("#idInsumo").val();
      var Precio_Compra = $("#Precio_Compra").val();
      var subtotal = Precio_Compra * cantidad;
      total = subtotal + total;
      console.info(total);
      $("#total").val(total);
    
      // quitar la inserción de aquí y mover abajo
    
      var id = "";
      var cantidad1 = 0;
      var precio1 = 0;
      
      // variable para indicar si se añadió fila en el bucle
      var encontrado = false;
    
      $("#tablaDatos tbody tr").each(function(i, e) {
        var tr = $(e);
        var td = $(e).find("td").eq(1);
    
        id = $(td).find("input").eq(0).val();
        cantidad1 = $(td).find("input").eq(1).val();
        precio1 = $(td).find("input").eq(2).val();
    
        var fila = "";
    
        if (id == IDInsumo) {
          // si se encontró un ID: encontrado!
          encontrado = true;
          
          var tcan = parseInt(cantidad) + parseInt(cantidad1);
          var tpre = parseFloat(precio1) + parseFloat(Precio_Compra);
    
          tr.remove();
          cont++;
          fila = '<tr class="selected" id="fila' + cont + '" onclick="seleccionar(this.id)"><td>' + cont + '</td><td><input type="hidden" value="' + IDInsumo + '"><input type="hidden" value="' + tcan + '"><input type="hidden" value="' + tpre + '">' + IDInsumo + '</td><td>' + tcan + '</td><td>' + tpre + '</td></tr>';
          $('#tbodydatos').append(fila);
          reordenar();
          return false;
        }
      });
      
      // si es el primer elemento o no se encontró ID, se añade una neuva fila
      // código de arriba movido aquí cambiando un poco la condición
      // realmente el 'cont == 0' ya no hace falta, porque si la tabla está vacía encontrado será false
      if (cont == 0 || !encontrado) {
        cont++;
        fila = '<tr class="selected" id="fila' + cont + '" onclick="seleccionar(this.id)"><td>' + cont + '</td><td><input type="hidden" value="' + IDInsumo + '"><input type="hidden" value="' + cantidad + '"><input type="hidden" value="' + Precio_Compra + '">' + IDInsumo + '</td><td>' + cantidad + '</td><td>' + subtotal + '</td></tr>';
        $('#tbodydatos').append(fila);
        // tenemos que reordenar
        reordenar();
        return;
      }
    }
    
    function reordenar() {
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <input type="text" id="idInsumo" placeholder="Insumo" />
    <input type="text" id="Cantidad" placeholder="Cantidad" />
    <input type="text" id="Precio_Compra" placeholder="Precio de Compra" />
    <button onclick="agregar()">Agregar fila</button>
    
    <hr/>
    
    <table id="tablaDatos" class="table table-bordered">
      <thead>
        <tr>
          <td>Numero del Insumo</td>
          <td>Insumo</td>
          <td>Cantidad</td>
          <td>Subtotal</td>
        </tr>
      </thead>
      <tbody id="tbodydatos"></tbody>
      <tfoot>
        <tr>
          <td colspan="3"></td>
          <td><input type="text" id="total" disabled /></td>
        </tr>
      </tfoot>
    </table>
        
    answered by 28.05.2017 / 14:25
    source