calculate values of a dynamic table

0

What I want to do is calculate the values of the SubTotal field, since this is the result of the multiplication between the values of the Price field and the value entered in field text Quantity . In addition to calculating the VAT of the sum of the Subtotals and the Total (Sum of the Subtotals and the IGV)

I'm new to JS and I do not know much about the language.

JS:

$('.a').on('click',function(){
var trPrincipal = this.offsetParent.parentElement; //Buscamos el TR principal
// var firstName = trPrincipal.children[0].outerText; //Capturamos el FirstName
var idproducto=trPrincipal.children[0].outerText;
var nombreprod=trPrincipal.children[1].outerText;
var peso=trPrincipal.children[3].outerText+' '+trPrincipal.children[2].outerText;
var precio=trPrincipal.children[5].outerText;

// var lastName = trPrincipal.children[1].outerText+' '+trPrincipal.children[2].outerText; //Capturamos el LastName

$(".othertable").append("<tr><td>"+
idproducto+"</td><td>"+
nombreprod
+"</td><td>"+
peso+"</td><td>"+
precio+"<td><input type='text' placeholder='Ingresar cantidad'/></td><td><input type='text' disabled value='458.15'></td><td><input type='button' class='btneli' id='idbotoneli' value='Eliminar'></td></tr>");
  trPrincipal.style.display = "none"; //Ocultamos el TR de la Primer Tabla
  var btn_ = document.querySelectorAll(".btneli"); // Buscamos todos los elementos que tengan la clase .btneli
  for(var a in btn_){ //Iteramos la variable btn_
var b = btn_[a];
if(typeof b == "object"){ //Solo necesitamos los objetos
  b.onclick = function (){ //Asignamos evento click
    var trBtn = this.offsetParent.parentElement; // buscamos el tr principal de la segunda tabla
    var firstNameBtn = trBtn.children[0].outerText; //Capturamos el FirstName de la segunda tabla
    trBtn.remove(); // eliminamos toda la fila de la segunda tabla
    var tbl = document.querySelectorAll(".table td:first-child"); //Obtenemos todos los primeros elementos td de la primera tabla
    for(var x in tbl){ //Iteramos los elementos obtenidos
      var y = tbl[x];
      if(typeof y == "object"){ //solo nos interesan los object
        if (y.outerText == firstNameBtn){ //comparamos el texto de la variable y vs el firstNameBtn
           var t = y.parentElement; //capturamos el elemento de la coincidencia
          t.style.display = ""; //actualizamos el estilo display dejándolo en vacío y esto mostrará nuevamente la fila tr de la primera tabla
        }
      }
    }
  }
}
  }
});
table{
  margin:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">


<div class="container">

<table id="idsecond" class="table table-bordered table-hover">
                  <thead bgcolor="skyblue">
                    <tr>
                <th>#</th>
                <th>Articulo</th>
                <th>Unidad M.</th>
                <th>Peso/Volumen</th>
                <th>Categoria</th>
                <th>P.Unitario</th>

                <th>Accion</th>
                      
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                    <td>1</td>
                    <td>Arroz</td>
                    <td>Kilo</td>
                    <td>4</td>
                    <td>---</td>
                    <td>18</td>
                    <td><button class="a">Agregar</button></td>
                    </tr>
                    <tr>
                    <td>2</td>
                    <td>Sal</td>
                    <td>Kilo </td>
                    <td>2</td>
                    <td>---</td>
                    <td>14</td>
                    <td><button class="a">Agregar</button></td>
                    </tr>
                    <tr>
                    <td>3</td>
                    <td>Maiz</td>
                    <td>Kilo</td>
                    <td>3</td>
                    <td>---</td>
                    <td>12</td>
                    <td><button class="a">Agregar</button></td>
                    </tr>
                  </tbody>
              </table>
              
              
              

<table class="othertable col-xs-12 table-condensed table-hover table-bordered">
            <thead bgcolor="orange">
            <tr>
                <th>#</th>
                <th>Nombre</th>
                <th>Peso/Volumen</th>
                <th>Precio</th>
                <th>Cantidad</th>
                <th>SubTotal</th>
                <th>Accion</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        
<hr>

  <div class="row">
  <div class="form-group col-sm-4">
    <label for="igv">IGV:</label>
    <input type="text" class="form-control"disabled id="igv">
  </div>
    <div class="form-group  col-sm-4">
    <label for="total">Total:</label>
    <input type="text" class="form-control" disabled id="total">
  </div>
  
</div>
</div>
    
asked by Raphael 24.06.2016 в 21:52
source

1 answer

1

You can verify here the operation of what you request, your script needs to update more things, such as when you delete a column you must also update the total and the IGV.

$('.a').on('click',function(){
var trPrincipal = this.offsetParent.parentElement; //Buscamos el TR principal
// var firstName = trPrincipal.children[0].outerText; //Capturamos el FirstName
var idproducto=trPrincipal.children[0].outerText;
var nombreprod=trPrincipal.children[1].outerText;
var peso=trPrincipal.children[3].outerText+' '+trPrincipal.children[2].outerText;
var precio=trPrincipal.children[5].outerText;

// var lastName = trPrincipal.children[1].outerText+' '+trPrincipal.children[2].outerText; //Capturamos el LastName

$(".othertable").append("<tr><td>"+
idproducto+"</td><td>"+
nombreprod
+"</td><td>"+
peso+"</td><td>"+
precio+"<td><input type='number' placeholder='Ingresar cantidad'/></td><td><p class='subTotal'></p></td><td><input type='button' class='btneli' id='idbotoneli' value='Eliminar'></td></tr>");
  trPrincipal.style.display = "none"; //Ocultamos el TR de la Primer Tabla
  var btn_ = document.querySelectorAll(".btneli"); // Buscamos todos los elementos que tengan la clase .btneli
  for(var a in btn_){ //Iteramos la variable btn_
var b = btn_[a];
if(typeof b == "object"){ //Solo necesitamos los objetos
  b.onclick = function (){ //Asignamos evento click
    var trBtn = this.offsetParent.parentElement; // buscamos el tr principal de la segunda tabla
    var firstNameBtn = trBtn.children[0].outerText; //Capturamos el FirstName de la segunda tabla
    trBtn.remove(); // eliminamos toda la fila de la segunda tabla
    var tbl = document.querySelectorAll(".table td:first-child"); //Obtenemos todos los primeros elementos td de la primera tabla
    for(var x in tbl){ //Iteramos los elementos obtenidos
      var y = tbl[x];
      if(typeof y == "object"){ //solo nos interesan los object
        if (y.outerText == firstNameBtn){ //comparamos el texto de la variable y vs el firstNameBtn
           var t = y.parentElement; //capturamos el elemento de la coincidencia
          t.style.display = ""; //actualizamos el estilo display dejándolo en vacío y esto mostrará nuevamente la fila tr de la primera tabla
        }
      }
    }
  }
} //Termina onclick
  }//Termina For

    //Emprezamos buscando todos los inputs tipo Number
  var a = document.querySelectorAll("input[type='number']");
  if(a != undefined || a != null){
a.forEach(function (x){ //De todo el resultado iteramos con un Foreach
  var precio = Number(x.parentElement.previousSibling.textContent); // Localizamos el Precio dentro de la tabla
  x.onkeyup = function (){ //Asignamos un Metodo del teclado; 
    this.offsetParent.nextElementSibling.children[0].innerHTML = (precio * x.value); //Calculamos el subtotal y se lo agregamos en la columna
    generarTotal(); // Ejecutamos una funcion que se genera el Total
  }
});//Foreach
  }//if

  function generarTotal(){ //Funcion que genera el total
var a = document.querySelectorAll(".subTotal"); //Buscamos todos los subtotales
if(a != undefined || a != null){
  var total = new Number(); //creamos variable tipo Number llamada Total
  a.forEach(function (x){ //Iteramos el array a que contiene los subtotales
    total += Number(x.textContent); // Vamos sumando todos los subtotales en la variable total
  });
  var t_ = document.getElementById("total"); //Buscamos el input que tiene Id: total
  t_.value = total.toFixed(2);  // le asignamos por la propiedad value el valos de todos los subtotales con 2 decimales
  generarIGV(); // Generamos el IVa General de las Ventas con la funcion generarIGV
}
  }

  function generarIGV(){ //Funcion que calcula el IVA
var a = document.getElementById("total"); //Buscamos el elemento Total para extraer el total de las ventas
var igv = 0.18; //AQUI se coloca el iva que deseas calcular, par este efecto he puesto el 18%. 
var b = document.getElementById("igv"); // Buscamos el campo con Id igv
var operacion = Number(a.value) * igv; // calculamos el IGV
b.value = operacion.toFixed(2); // Le asignamos al campo con Id igv el IVA mediante la propiedad value.

}
});
table{
  margin:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">


<div class="container">

<table id="idsecond" class="table table-bordered table-hover">
                  <thead bgcolor="skyblue">
                    <tr>
                <th>#</th>
                <th>Articulo</th>
                <th>Unidad M.</th>
                <th>Peso/Volumen</th>
                <th>Categoria</th>
                <th>P.Unitario</th>

                <th>Accion</th>
                      
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                    <td>1</td>
                    <td>Arroz</td>
                    <td>Kilo</td>
                    <td>4</td>
                    <td>---</td>
                    <td>18</td>
                    <td><button class="a">Agregar</button></td>
                    </tr>
                    <tr>
                    <td>2</td>
                    <td>Sal</td>
                    <td>Kilo </td>
                    <td>2</td>
                    <td>---</td>
                    <td>14</td>
                    <td><button class="a">Agregar</button></td>
                    </tr>
                    <tr>
                    <td>3</td>
                    <td>Maiz</td>
                    <td>Kilo</td>
                    <td>3</td>
                    <td>---</td>
                    <td>12</td>
                    <td><button class="a">Agregar</button></td>
                    </tr>
                  </tbody>
              </table>
              
              
              

<table class="othertable col-xs-12 table-condensed table-hover table-bordered">
            <thead bgcolor="orange">
            <tr>
                <th>#</th>
                <th>Nombre</th>
                <th>Peso/Volumen</th>
                <th>Precio</th>
                <th>Cantidad</th>
                <th>SubTotal</th>
                <th>Accion</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        
<hr>

  <div class="row">
  <div class="form-group col-sm-4">
    <label for="igv">IGV:</label>
    <input type="text" class="form-control"disabled id="igv">
  </div>
    <div class="form-group  col-sm-4">
    <label for="total">Total:</label>
    <input type="text" class="form-control" disabled id="total">
  </div>
  
</div>
</div>
    
answered by 25.06.2016 / 01:40
source