Reputation: 2720
I met a trouble to compare number in jquery. test code here:
<script src="jquery.js"></script>
<script>
jQuery(document).ready(function(){
var val1 = $("#aaa").attr('title');
var val2 = $("#bbb").html();
if(val1>=val2){
$("#ccc").html(val1);
}else{
$("#ccc").html(val2);
}
});
</script>
<div id="aaa" title="1">aaa</div>
//set title=1 show 1, set title=2 show 111
<div id="bbb">111</div>
<div id="ccc"></div>
As code show, two number from html dom. now I set number in div#aaa[title]
, if set number one, it is right, and if set number 2, the result is wrong. Where is the problem? Thanks.
Upvotes: 5
Views: 29051
Reputation: 30185
You need to compare int
values, not a strings
jQuery(document).ready(function(){
var val1 = parseInt($("#aaa").attr('title'));
var val2 = parseInt($("#bbb").html());
if(val1>=val2){
$("#ccc").html(val1);
}else{
$("#ccc").html(val2);
}
});
Code: http://jsfiddle.net/BCKKr/
Upvotes: 9
Reputation: 16480
You are comparing strings, convert them to int with parseInt(value, 10);
var val1 = parseInt($("#aaa").attr('title'), 10);
var val2 = parseInt($("#bbb").html(), 10);
Upvotes: 13