Javascript: The check 2 12 returns true

3

In a part of my code I have to check if a number entered by the user is greater than a maximum. I have this written:

    console.log("mod: "+ mod);
    console.log("max_mod: "+ max_mod);
    console.log("mod > max_mod: "+ (mod > max_mod));

When I write 2 or a number between 2 and 9 the result of the console.log is as follows:

  • mod: 2
  • max_mod: 12
  • mod > max_mod: true

However, if I write 1, 10 or 11 the result is this, which is normal:

  • mod: 1
  • max_mod: 12
  • mod > max_mod: false

I do not know why this happens, the numbers I pick up from different variables like this:

var mod = $(this).parents(".modal-content").find("#input_num_mod").val();
var max_mod = $(this).parents(".modal-content").attr('data_mod');

Does anyone know why this may be happening?

    
asked by Victor Galvez Lopez 29.05.2018 в 10:11
source

1 answer

3

Your problem is that the comparison is being made at the level of Strings not of numbers

Try to parse the whole values with parseInt

var mod = parseInt($(this).parents(".modal-content").find("#input_num_mod").val());
var max_mod = parseInt($(this).parents(".modal-content").attr('data_mod'));

Eye, you should check that they are numbers too.

    
answered by 29.05.2018 / 10:32
source