JavaScript does not compare minimum values ​​that exceed maximum values

Why "more than" comparing numbers in JavaScript does not work. The following example returns true even when the mini number is less than the maximum.

mini and maxi are input form values. This example uses jQuery to get the values, but it can be easily removed.

var mini = $('form#filterPrice input.min').val(); //eg. 500 var maxi = $('form#filterPrice input.max').val(); //eg. 1500 if( mini.valueOf() > maxi.valueOf() ) { //also used: mini > maxi alert('test'); //alerts "test" even when mini is less than maxi $('form#filterPrice input.min').val( maxi ); //should switch values if mini > maxi $('form#filterPrice input.max').val( mini ); } 

Replacing "mini> maxi" with "Math.max (mini, maxi) == mini" works fine. So the following works:

 var mini = $('form#filterPrice input.min').val(); //eg. 500 var maxi = $('form#filterPrice input.max').val(); //eg. 1500 if( Math.max(mini, maxi) == mini ) { alert('test'); $('form#filterPrice input.min').val( maxi ); $('form#filterPrice input.max').val( mini ); } 
0
javascript comparison math
source share
2 answers

Use this string to get Int from String

 if( parseInt(mini.valueOf(),10) < parseInt(maxi.valueOf(),10) ) { //also used: mini > maxi 

sinve you get the values ​​compared to dom as a string. Fist, you have to parse them into Int and only then compare. It is also better to put 10 as the second parameter to make sure that the number will be parsed as a decimal.

+4
source share

in the first example, you are comparing strings and "1500" < "500" . In the second example, Math.max converts values ​​to numbers.

0
source share

All Articles