Reputation: 385
my html code is like:
<html>
<SCRIPT type="text/javascript" language="JavaScript">
function fun()
{
var l = document.test.low.value;
var h = document.test.high.value;
alert(l);
alert(h);
if(l >h){
alert("low greater than high low is -"+l+"high is -"+h);
}
}
</SCRIPT>
<body>
<form name="test">
<input type="text" size="11" id="low" />
<input type="text" size="11" id="high" />
<input type="button" value="sss" onClick="fun()"/>
</form>
</body>
</html>
when i compare this two values using low is 12 and high is 112 is not working. like 22 and 122, 33 and 133 etc....
I am using IE browser version 8. please help.
Upvotes: 18
Views: 94102
Reputation: 8871
Convert the values to numbers:
if(Number(l) > Number(h)){ /* … */ }
or alternatively, parse each string as a float:
if(Number.parseFloat(l) > Number.parseFloat(h)){ /* … */ }
or as an integer:
if(Number.parseInt(l, 10) > Number.parseInt(h, 10)){ /* … */ }
Upvotes: 32
Reputation: 816
When you compare two strings in an if statement:
if ( l > h) {}
when l = "12" and h = "112"
It compares these two values as strings as "3" > "1"
. It says l > h
is true
Upvotes: 0
Reputation: 21
var lnum = new Number(l);
var hnmu = new Number(h);
if(lnum > hnum){
alert('if');
}else{
alert('else');
}
Upvotes: 1
Reputation: 382606
Use parseInt
with base to get correct results:
var l = parseInt(document.test.low.value, 10);
var h = parseInt(document.test.high.value, 10);
Upvotes: 6
Reputation: 66389
You need to convert them to numbers:
if(+l > +h){
The unary plus operator will convert the string value to numeric value. See this question for more details:
What's the significant use of unary plus and minus operators?
Upvotes: 11