Jquery ignoring houses on the right

Asked

Viewed 35 times

4

I set the function below, for validation of values in two fields, one automatic (comes from the bank) and the other typed by the user. What happens is that, apparently, it 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 function above, the field qtde_trans value 50. The field qtde displays 2000. In Alerts the values are exactly those. But somehow it enters the if, as if the qtde was smaller. Now, if I type 20, it accepts. But if you type 21 it displays the error. I tried to clear variables, as it is above still, I tested other methods to compare, but it did not take effect. Any suggestions?

  • 2

    Have you tried converting to Number both? Number($(this).val()) ? Oh, and also, made sure that there is no more than one field named Qtde[]?

  • Thanks, I just put the Number in both, it worked. There is only one field with the name Qtde. You can post as reply :)

2 answers

5


You can convert to Number both values:

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

And then make your parole:

if (qtde < qtde_trans) { ... }

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

4

It doesn’t ignore houses. Unless there’s 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 smaller (comes before) than 500.

Tip: guarantee the numerical type of variables through the functions parseint if it is to work only in one piece, and parseFloat otherwise.

i and..:

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

 * there are plugins for jQuery that make the value of specific text inputs already obtainable as numerical values through the method val.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.