1

I have 2 numeric input fields and the below runs when the user stops inputting. What I am doing is checking that input a number is not bigger than input b and if it is show error.

The issue is that calculation is not happening well. For instance it works if a is 200 and b is 100 but not if a is 200 and b is 5

Not sure why... so any help would be greatly appreciated.

$("#input_6_23, #input_6_24").on({  
  blur: function() {
        var a = document.getElementById("input_6_23").value;
        var b = document.getElementById("input_6_24").value;

        if(a > b) {     
            alert(a is bigger than b);          
        }
  }
});
Jason
  • 433
  • 6
  • 19
  • 1
    Possible duplicate of [issue with comparing two numbers in javascript](http://stackoverflow.com/questions/9094299/issue-with-comparing-two-numbers-in-javascript) – trincot May 01 '16 at 14:31

3 Answers3

6

its working so?

 jQuery(document).ready(function($){

    $("#input_6_23, #input_6_24").on('blur',function() {

      check();
    });
    function check(){
       var a = Number($("#input_6_23").val());
       var b = Number($("#input_6_24").val());

       if(a > b) {     
        alert(a+' is bigger than '+b);          
       } else {
        alert("error");
    }  
}});
wui
  • 400
  • 3
  • 11
2

Change into:

var a = parseInt(document.getElementById("input_6_23").value, 10);
var b = parseInt(document.getElementById("input_6_24").value, 10);
Gerard
  • 15,418
  • 5
  • 30
  • 52
0

You are doing string comparisons, not numeric comparison. You can convert to a number before comparing like this (note the addition of + signs when retrieving the .value):

$("#input_6_23, #input_6_24").on({  
  blur: function() {
        var a = +document.getElementById("input_6_23").value;
        var b = +document.getElementById("input_6_24").value;

        if(a > b) {     
            alert("a is bigger than b");          
        }
  }
});

P.S. You also have to make your a is bigger than b into a valid string with quotes around it.

There are multiple ways to convert a string to a number:

var num = parseInt(str, 10);
var num = +str;
var num = Number(str);

And, hopefully this is just for testing because putting an alert() on a blur event is pretty obnoxious in an actual real use scenario.

jfriend00
  • 683,504
  • 96
  • 985
  • 979