Reputation: 39
I found that when jQuery get a value with 0 (for example 100)trail, it will omit it. So if I compare 5>100, the result is true. So how do I solve this? here is the HTML code:
<form id="target">
<input type="text" id="max" value="100"/>
<input type="text" id="number" />
<input id="submit" type="submit" value="submit" />
</form>
And here is jquery:
$('#target').submit( function() {
var a = $("#number").val();
var b = $("#max").val();
if( a > b){
alert("exceed limit");
}
return false;
});
Here you can see demo: http://jsfiddle.net/yqMGG/91/
Upvotes: 1
Views: 80
Reputation: 1998
You can multiply it by 1 to convert it from string to number, or use parseInt
var a = $("#number").val() * 1;
OR
var a = parseInt($("#number").val(), 10);
the second parameter of parseInt function is the radix.
Upvotes: 0
Reputation: 120496
You need to compare the numeric values, not the string values. The output of the .val()
function is a DOMString value according to DOM Level 2 which says:
interface HTMLInputElement : HTMLElement { ... attribute DOMString value; ... }
so your (5 > 100) test is really "5" > "100"
which is true since strings are compared lexicographically.
The solution is to change
if( a > b){
to
if(+a > +b){
The +
prefix operator coerces its argument to a number.
Upvotes: 3
Reputation: 5291
Use parseFloat()
, otherwise the values are considered as strings.
$('#target').submit( function() {
var a = parseFloat($("#number").val());
var b = parseFloat($("#max").val());
if( a > b){
alert("exceed limit");
}
return false;
});
See Demo
Upvotes: 0