Yair Villar
Yair Villar

Reputation: 195

jquery input value comparison only gets one digit

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

Answers (6)

wsanville
wsanville

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

charlietfl
charlietfl

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

R&#233;mi Breton
R&#233;mi Breton

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

Sven Bieder
Sven Bieder

Reputation: 5681

Your error is, that you are comparing strings.

Use parseInt(), or parseFloat()

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

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

James Montagne
James Montagne

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

Related Questions