Jquery ignoring houses on the right

4

I set up the function below, for validation of values in two fields, one automatic (comes from the bank) and another one entered by the user. What happens is that apparently he ignores the houses to the right of the value. For example:

function calc_dif() {
  if ($(this).val().length > 0) {
       qtde = null; //ZERA AS DUAS VARIAVEIS PARA NÃO PEGAR LIXO DA MEMORIA
       qtde_trans = null; //ZERA AS DUAS VARIAVEIS PARA NÃO PEGAR LIXO DA MEMORIA

       var qtde_trans = $(this).val(); //VALOR DIGITADO
       var qtde = $(this).closest('tr').find('[name="qtde[]"]'); //campo ao lado
       alert(qtde_trans);
       alert(qtde.val());
       if (qtde.val() < qtde_trans) {
          alert("Não pode transferir mais que o disponível!");
          $(this).val(null);
          $(this).focus();
          qtde = null;
          qtde_trans = null;
       }
  }
}

In the above function, the qtde_trans field receives the value 50. The qtde field displays 2000. In the alerts the values are exactly those. But somehow it goes into if, as if qtde is less. Now, if I type 20, he accepts. But if you type 21 it displays the error. I tried cleaning variables, as above, I tested other methods to compare, but it did not work. Any suggestions?

    
asked by anonymous 19.06.2017 / 14:24

2 answers

5

You can convert both values to Number:

var qtde_trans = Number($(this).val()); //VALOR DIGITADO
var qtde = Number($(this).closest('tr').find('[name="qtde[]"]').val()); 

And then make your conditional:

if (qtde < qtde_trans) { ... }

This will ensure that your values are tested as numbers. (=

    
19.06.2017 / 14:34
4

He does not ignore homes. Unless there is more code you want to show us, I believe the comparison is made between texts, not numbers.

When you compare texts, the comparison is in alphabetical order. And in alphabetical order 2000 is less (comes before) than 500.

Tip: Ensure the numeric type of variables through the functions parseInt if working with integers only, and parseFloat otherwise

i.e.:

var valorNumerico = parseInt(foo.val()); // trabalhe agora com o valor numerico.

* There are jQuery plugins that make the value of specific text inputs already obtainable as numeric values using the val method.

    
19.06.2017 / 14:30