When I remove a row of 'tr', it generates an error when adding them - jQuery

1

Hello, I'm trying to Remove a row from a table, I remove it visually, the code works fine but I have a function that is add This function is triggered every time I click on the add button, everything goes fine if I remove the last row but if remuevo the one above or any other I get as total "NaN" I hope you can help me. Thanks.

HTML CODE:

<div class="col-xs-7">
     <table id="table_ventas"
        class="table table-bordered table-condensed table-hover responsive"
            cellspacing="0" width="100%">
             <thead>
               <tr>
                  <th><FONT SIZE=4>#</FONT></th>
                  <th><FONT SIZE=4>Código</FONT></th>
                  <th width="320px"><FONT SIZE=4>Producto</FONT></th>
                  <th><FONT SIZE=4>Precio</FONT></th>
                  <th><FONT SIZE=4>Cantidad</FONT></th>
                  <th><FONT SIZE=4>Subtotal</FONT></th>
                  <th width="5%"></th>
                </tr>
              </thead>
              <tbody>
              </tbody>
             </table>
       <div class="row">
         <div align="center" id="modal_footer">
                 <table id="table_total"
            class="table table-bordered table-condensed table-hover responsive"
               cellspacing="0" width="100%">
           <thead>
              <tr>
              <td id="total_fila" style="text-align: right;"><strong><FONT SIZE=6>TOTAL : s./ </FONT></strong></th>
                <td id="detalle_total"><strong><FONT color="#1b5e20" SIZE=6> 0 </FONT><th>  
           </tr>
           </thead>
           </table>
            <div align="center">
       <button type="button" id="btnSave" onclick="cancelar_venta()"
     class="btn btn-danger btn-lg"><i class="fa fa-remove"></i> CANCELAR COMPRA</button>
    </div>
    </div>
    </div>
    </div>

ADD BUTTON CODE

$("#confirmar_producto").click(function () {
    /* Capturar los valores de los campos */
    var id_producto = $('#id_producto').val();
    var cod_producto = $('#cod_producto').val();
    var precio = $('#precio').val();
    var cantidad = $('#cantidad_comprar').val();
    var producto = $("#producto").text();
    var subtotal = precio * cantidad;
    /* Crear una fila nueva con los datos capturados */
    var cont_fila = ($('#table_ventas tbody').find('tr').length) + 1;
    var fila = '<tr>';
    fila = fila + '<td scope="row">' + cont_fila + '</td>';
    fila = fila + '<td><input type="hidden" id="id_producto_tabla" value="' + id_producto + '"><input type="text" class="form-control text-center" id="Codigo_' + cont_fila + '" value="' + cod_producto + '" readonly="readonly" /></td>';//Codigo
    fila = fila + '<td><input type="text" class="form-control text-center" id="Producto_' + cont_fila + '" value="' + producto + '" readonly="readonly" /></td>';//Producto
    fila = fila + '<td><input type="text" class="form-control text-center" id="Precio_' + cont_fila + '" value="' + precio + '" readonly="readonly" /></td>';//Precio
    fila = fila + '<td><input type="text" class="form-control text-center" id="Cantidad_' + cont_fila + '" value="' + cantidad + '" readonly="readonly" /></td>';//Cantidad
    fila = fila + '<td><input type="text" class="form-control text-center" id="Subtotal_' + cont_fila + '" value="' + subtotal + '" readonly="readonly" /></td>';//Subtotal
    fila = fila + '<td><a href="javascript:void(0);" class="eliminar_fila" onclick="eliminar_detalle(this,' + cont_fila + ');"><i class="fa fa-trash-o fa-2x"></i></a></td>';//Eliminar
    fila = fila + '</tr>';
    /* Agregar las futuras filas */
    $("#table_ventas").append(fila);
    /* Despues de agregar limpiar los inputs*/
    limpiar();
    suma_total();
});

ADD FUNCTION CODE

function suma_total() {

    var cont_fila = ($('#table_ventas tbody').find('tr').length);
    var total_general = 0;
    for (var i = 1; i <= cont_fila; i++) {
        var subtotal = $('#Subtotal_' + i).val();
        total_general = parseFloat(total_general) + parseFloat(subtotal);
    }
    $("#detalle_total").html("<strong><FONT color='#1b5e20' SIZE=6> " + (total_general * 1).toFixed(2) + " </FONT>");
}

CODE OF DELETION

function eliminar_detalle(e, index) {

    $(e).parent().parent().remove();
    suma_total();

}
    
asked by Joel More F. 13.06.2017 в 22:05
source

2 answers

0

The problem is the variable cont_fila , which is based on the total rows + 1.

Suppose you have 3 rows, then:

  • id of input for 1er row use 1
  • id of input for 2da row use 2
  • id of input for 3ra row use 3

Suppose you delete the 1er row, when trying to add.

You will find the $('#Subtotal_1').val() , but this element no longer exists, so the result returned is undefined and that is why you then get as a total NaN .

Solution:

Modify the function that adds rows , so that input stop using id to identify them and instead use name .

$("#confirmar_producto").click(function () {
    /* Capturar los valores de los campos */
    var id_producto = $('#id_producto').val();
    var cod_producto = $('#cod_producto').val();
    var precio = $('#precio').val();
    var cantidad = $('#cantidad_comprar').val();
    var producto = $("#producto").text();
    var subtotal = precio * cantidad;
    /* Crear una fila nueva con los datos capturados */
    var cont_fila = ($('#table_ventas tbody').find('tr').length) + 1;
    var fila = '<tr>';
    fila = fila + '<td scope="row">' + cont_fila + '</td>';
    fila = fila + '<td><input type="hidden" name="id_producto_tabla" value="' + id_producto + '"><input type="text" class="form-control text-center" name="Codigo" value="' + cod_producto + '" readonly="readonly" /></td>';//Codigo
    fila = fila + '<td><input type="text" class="form-control text-center" name="Producto" value="' + producto + '" readonly="readonly" /></td>';//Producto
    fila = fila + '<td><input type="text" class="form-control text-center" name="Precio" value="' + precio + '" readonly="readonly" /></td>';//Precio
    fila = fila + '<td><input type="text" class="form-control text-center" name="Cantidad" value="' + cantidad + '" readonly="readonly" /></td>';//Cantidad
    fila = fila + '<td><input type="text" class="form-control text-center" name="Subtotal" value="' + subtotal + '" readonly="readonly" /></td>';//Subtotal
    fila = fila + '<td><a href="javascript:void(0);" class="eliminar_fila" onclick="eliminar_detalle(this);"><i class="fa fa-trash-o fa-2x"></i></a></td>';//Eliminar
    fila = fila + '</tr>';
    /* Agregar las futuras filas */
    $("#table_ventas").append(fila);
    /* Despues de agregar limpiar los inputs*/
    limpiar();
    suma_total();
});

Then modify the function suma_total so that it looks for the input for its name .

function suma_total() {
  var $trs = $('#table_ventas tbody').children();
  var cont_fila = $trs.length;
  var total_general = 0;

  for (var i = 0; i < cont_fila; i++) {

    var subtotal = $trs.eq(i).find('input[name="Subtotal"]').val();
    total_general += parseFloat(subtotal);
  }
  $("#detalle_total").html("<strong><FONT color='#1b5e20' SIZE=6> " + (total_general * 1).toFixed(2) + " </FONT>");
}
    
answered by 13.06.2017 в 22:35
0

Your for is wrong, you have i <= cont_fila and it must be i < cont_fila remember that the fixes are base 0, if you have 4 TR they go from 0 to 3 and when wanting to read the value of a row that does not exist you will have a undefined.

function suma_total() {

var cont_fila = ($('#table_ventas tbody').find('tr').length); //Tienes el TOTAL de TR
var total_general = 0;
//Tienes que ser i < cont_fila
for (var i = 1; i <= cont_fila; i++) {
    var subtotal = $('#Subtotal_' + i).val(); //la ultima iteración será undefined
    //Tienes que validar que exista subtotal 
    total_general = parseFloat(total_general) + parseFloat(subtotal);
    }
$("#detalle_total").html("<strong><FONT color='#1b5e20' SIZE=6> " + (total_general * 1).toFixed(2) + " </FONT>");
}

Try this

function suma_total() {

var cont_fila = ($('#table_ventas tbody').find('tr').length);
var total_general = 0;
for (var i = 1; i < cont_fila; i++) {
    var subtotal = $('#Subtotal_' + i).val();
    if(subtotal)
        total_general = parseFloat(total_general) + parseFloat(subtotal);
    }
$("#detalle_total").html("<strong><FONT color='#1b5e20' SIZE=6> " + (total_general * 1).toFixed(2) + " </FONT>");
}
    
answered by 11.07.2017 в 23:37