0

I have 2 html input fields, one in disabled and gets value from a php file using jQuery ajax and the other one is filled by the user.

I made a jQuery script which compares these two fields and should show a message if the user input is greater than the ajax filled input. The problem is that it returns a strange result, for example if the ajax field is 12300 and the input field is 8 it shows the message, but if ajax is 12300 and the input is 12229 than it does not show the message.

$(document).ready(function(){
    $("#cantitate").blur(function(){
    var cant_ins = $("#cantitate").val();
    var cant_suger = $("#info_cantitate").val();
    if (cant_ins > cant_suger){
        $("#status_cant").text("Cantitatea depaseste disponibilitatea");
    }
        else
    {
        $("#status_cant").empty();
    }
        });
});
1
  • .val() from a input will return a string, not a number Commented Feb 3, 2015 at 9:21

1 Answer 1

3

You're comparing strings, not numbers, that's why you get strange results, 1200 would be less than 200 as the first one starts with the character 1 and the second one with 2 etc.

You can use parseInt for integers or parseFloat for floats to parse the strings as numbers, or you can just use the + sign to coerce the strings to numbers

$(document).ready(function(){
    $("#cantitate").on('blur', function(){
        var cant_ins   = +$("#cantitate").val();
        var cant_suger = +$("#info_cantitate").val();

        if (cant_ins > cant_suger){
            $("#status_cant").text("Cantitatea depaseste disponibilitatea");
        } else {
            $("#status_cant").empty();
        }
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

love the + syntax for coercing strings
@atmd it is actually "tricky" and will likely confuse people who have never seen it before, whereas parseInt(value, 10) would not likely lead to confusion.
@self - well, they've seen it now. There's actually more issues with parseInt as people tend to forget the radix and get strange results, but generally I would have used parseInt in an answer, but the OP isn't clear on wether or not the inputs only accepts integers, or if floats are allowed as well
@self true, but then the same could be said for Ternary operators or decision tables. every aspect of coding can confuse people who haven't seen it before.

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.