compare if one value is less than another in a jquery table

1

Good morning, I need help to do the following:

I need to compare if a value of one column is less or greater than another column within a table.

I have advanced the following code:

$('.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 stock=trPrincipal.children[6].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>"+
stock+"</td><td>"+precio+"</td><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.

}
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


<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>Stock</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>12</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>0</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>8</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>Stock</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>

I would greatly appreciate the help.

    
asked by Raphael 24.07.2016 в 23:46
source

1 answer

2

Something you can do with jQuery is the following:

  • Optional (although convenient): add a class to input
  • Add a handler for the event change / keyup / keydown / input (or the one you like) that will do the following:
  • Read the contents of the fourth cell of the column (where the stock is)
  • Compare the value of input with the value obtained in 2.1
  • If it is greater: then the entered number is not valid
  • If it's less than or equal: everything is fine
  • The controller code would look like this:

    // controlador del evento input en la caja de texto
    $(".cantidad-check").on("input", function() {
        $this = $(this);
        // leemos el valor del stock y lo parseamos como entero
        var stock = parseInt($this.closest("tr").find("td:nth-child(4)").text());
        // comprobamos si el valor introducido es mayor que el del stock disponible
        if ($this.val() > stock) {
            // si lo es, realiza alguna acción (p.e.: mensaje de error, bordes rojos, etc.)
        } else {
            // si no lo es, no hagas nada o vuelve al estado inicial (p.e. sin bordes rojos)
        }
    });
    

    And here I leave a demo. The edges turn red when the number is greater than the stock, you can put another action such as putting the maximum value of the stock:

    $('.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 stock=trPrincipal.children[6].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>"+
    stock+"</td><td>"+precio+"</td><td>"+"<input type='number' class='cantidad-check' 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.
    
    }
      
      
      
      $(".cantidad-check").on("input", function() {
        $this = $(this);
        var stock = parseInt($this.closest("tr").find("td:nth-child(4)").text());
        if ($this.val() > stock) {
          // esto se ejecuta cuando la cantidad es mayor que el stock
          // para pruebas, yo pongo el borde rojo
          $this.css("border-color", "red");
        } else {
          // esto se ejecuta cuando la cantidad es menor o igual que el stock
          $this.css("border-color", "");
        }
      });
      
    });
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    
    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    
    <!-- Latest compiled JavaScript -->
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    
    
    <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>Stock</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>12</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>0</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>8</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>Stock</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.07.2016 / 00:14
    source