1

I have the following input:

<input type="number" class="form-control custom-values" name="Width" id="item-b" min="1201" max="1500" value="1361">

I'm trying to make sure that the value input by the user is within the min max boundaries. However, I'm running into an odd issue.

When I use this script to check the values:

if($(this).val() > $(this).attr("max") || $(this).val() < $(this).attr("min")){
        alert("out of bounds");
        all_custom_sizes_valid = false;
    }else if($(this).val() < $(this).attr("max") || $(this).val() > $(this).attr("min")){
        if(!all_custom_sizes_valid){
            alert("fixed to in bounds");
            all_custom_sizes_valid = true;
        }else{
            alert("in bounds");
        }
    }

Things generally work fine.

However, when I input 150 into the input box, it gives me an alert that the value is within bounds. 150 is the only number I've been able to find that does this.

I've also had other issues with the validation not updating properly when I change back to a valid value and the "Fixed to in bounds" alert not popping up.

Any insight would be greatly appreciated.

4 Answers 4

4

You are comparing strings. Both $(this).val() and $(this).attr("max") are string (as is the value of the min attribute).

Looking at the tests this way, both of these are true: "150" > "1201" and "150" < "1500" (you can try in the browser console). You can use parseInt() to get integer values that you can compare.

Another problem is you should have && instead of || between comparisons (you want it to be greater than min and also smaller than max).

Also it would look nicer (to me at least :) ) if you got the values into variables first, there you could apply the int conversion too: var currentValue = parseInt($(this).val()), etc.

Sign up to request clarification or add additional context in comments.

1 Comment

This appears to have fixed it so far. I'm going to test it for a little to make sure. Thanks for such a quick answer.
1

Right now all your comparisons are strings, not numbers. Try using parseInt or similar operations to convert each value to a number before comparison

Comments

0

Your else if statement shouldn't be using ||.

It should be

else if($(this).val() < $(this).attr("max") && $(this).val() > $(this).attr("min")){

Comments

0

I think the reason why 150 passes is because of this line

if($(this).val() < $(this).attr("max") || $(this).val() > $(this).attr("min")){

It leaks through because of the OR operator.'If 150 is < 1500 Or 150 > 1200' then do stuff...

Javascript sees that the first condition is satisfied and thus proceed to enter the if loop. Replace with an AND '&&' operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.