Reputation: 195
hi im new to jquery and im facing these problem
i have these code
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(".adults").change(function(){
var test = $(".maxpeople").val();
if ($(this).val() > $(".maxpeople").val()) {
alert("test");
}
alert(test)
});
</script>
and i need to compare the digits and if the value of .adults is bigger than the value of .maxpeople then show me an alert. the code works but it looks like it only takes one digit. exjample:
.maxpeople = 17
i put 1 in .adults and is ok but if i put 2 it shows the alert, now if i put 16 it doesnt show the alert.. what im i doing wrong??
Upvotes: 0
Views: 2327
Reputation: 37516
You need to compare integers, not strings. Consider the following example:
console.log("12" > "2"); //false
console.log(12 > 2); //true
You should use the parseInt function to fix this, i.e:
var test = parseInt($(".maxpeople").val(), 10);
Upvotes: 1
Reputation: 171690
The values are being treated as strings unless told otherwise
Try this:
$(".adults").change(function(){
var test = $(".maxpeople").val();
if ( parseInt($(this).val(),10) > parseInt($(".maxpeople").val(),10)) {
alert("test");
}
alert(test)
});
Upvotes: 2
Reputation: 4259
I believe your problem originates from the fact that .val()
returns a string
. Use parseInt()
like so:
if (parseInt($(this).val()) > parseInt($(".maxpeople").val())) {
alert("test");
}
Upvotes: 0
Reputation: 5681
Your error is, that you are comparing strings.
Use parseInt(), or parseFloat()
Upvotes: 0
Reputation: 114417
.val()
is going to be a string. You need to make it a number if you want numeric comparisons.
parseInt($(this).val()) > parseInt($(".maxpeople").val())
Upvotes: 0
Reputation: 78690
val()
is going to return a string. If you want to compare numbers, you will have to convert the strings to numbers.
Assuming you just want integers, use parseInt
.
Upvotes: 4