Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Jquery if statement failed

i have the following input tag:

<input id="item_amount" type="text" id="item_stk" placeholder="1" value="" class="input-small" placeholder="" style="float: left;">

now to make sure that this input fields value is less than a certain amount i made the following Jquery function:

var max_amount = $('#max_amount').val();

$( "#item_amount" ).keyup(function() {
       if($(this).val() > max_amount){
        $(this).val( max_amount);
    }
});

Now max value is set to 2

if i write 4 in the input field it correctly returns the value to 2.

However if start by writing 1 then 2 then 3 then 4 ect ect ect. then it never gets into the if statement and resets the value.

ie. the value of the input field is now 1234 (which is far more than 2).

So what am i doing wrong?

Upvotes: 1

Views: 78

Answers (2)

Vidya
Vidya

Reputation: 30310

Make sure your inputs are of type number:

<input type="number" step="any" id="max_amount" />

Then do a parseFloat($('#max_amount').val()) to convert the string into an actual decimal value.

Of course, this has to be done with all inputs you want to treat as numbers.

It is better to use type="number" so you don't have to worry about isNaN tests in your code on the call to parseFloat.

Hope that helps.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382170

Right now, you're comparing strings, and the comparison isn't numeric : "10" < "2"

You need to parse the values :

var max_amount = parseFloat($('#max_amount').val());
if (parseFloat($(this).val()) > max_amount){

Upvotes: 3

Related Questions