How to use comparison operator in Javascript for two input values

后端 未结 4 1500
梦如初夏
梦如初夏 2021-01-27 04:01

I want to compare the two input values, just try in javascript, but it\'s not working fine. I\'m using the following code

function check_closing()
{
var opening         


        
4条回答
  •  无人及你
    2021-01-27 04:38

    You're comparing the strings instead of integers, so you need to convert the strings to integers. Since as strings, '8541' > '8241'

    >>>'8541' > '8241'
    true
    >>>'954' > '8241'
    true
    
    >>>8541 > 8241
    true
    >>>954 > 8241
    false
    

    So you want:

    function check_closing()
    {
        var opening = parseInt($('#opening').val());
        var closing = parseInt($('#closing').val());
        if(opening > closing)
        {
            alert('Opening is greater than Closing. Please enter the correct value');
            $('#closing').val('');
        }
    }
    

    To add more to why exactly this happened, in case you're interested: Strings are compared character by character, iirc. So the '9' is greater than the '8' but the '8241' is less than '8541' because '2' is less than '5'.

提交回复
热议问题