How to capture a variable type int in js?

3

Well, I do not know if I made myself understood correctly, so I explain. I am working with what is HTML, JS, PHP and MySQL. At the moment my only problem would be with JS. I'm trying to use an if, to compare 2 numbers, one has to be yes or if less than the other, otherwise it jumps an error message. (An alert in this case [Quantity not valid, you are trying to carry more than the existing amount (2)]) Everything was fine, until the moment I discovered that it did not work at all "well" or good in my opinion. When I decided to do the comparison of a two-digit number with one of one. Example: 2 is less than 13, that's obvious. But apparently JS interprets that 2 is greater than 13 because it interprets that 2 is greater than 13 because the 13 has a "1" and therefore JS ends up giving me the error message of the case where the first number is greater than the second. The "solution" was to put a 0 before 2 and there if JS, know that 2 is less than 13.

var cantidadea = $('#xcant2').val();
if($('#xcanta2').val()> cantidadea)
{
    alert("Cantidad no valida, estas tratando de llevar mas de la cantidad existente (2)");
    return false;
}
else
{
    if($('#xcanta2').val()<0)
    {
        alert("Numero no valido. (Fila 2)");
        return false;
    }
    else
    {
        cantidadb2 = $('#xcanta2').val();
        coment2    = $('#xcoment2').val();
        modelo2    = $('#xvalmerc2').val();
        cantidade2 = $('#xcant2').val();
    }
}
    
asked by Edgar Felipe Hernandez Garcia 12.04.2018 в 23:14
source

2 answers

2

Another option you can do is use the parseFloat (variable) function that returns a string (string) in floating number.

Example:

var cantidadea = parseFloat($('#xcant2').val());

if(parseFloat($('#xcanta2').val()) > cantidadea)
{
     alert("Cantidad no valida, estas tratando de llevar mas de la cantidad existente (2)");
     return false;
}
    
answered by 12.04.2018 / 23:25
source
1

The inputs always keep text type values, so you have to convert them first to number. A simple way to do this is simply to put a + sign in front:

let v1=$('#campo1').val();
let v2=$('#campo2').val();

console.log('Como texto',v1+v2);
let resultado=+v1 + +v2;
console.log('como números', resultado);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="campo1" value="10">
<input id="campo2" value="12">
    
answered by 12.04.2018 в 23:21