Skip to content Skip to sidebar Skip to footer

Check If Number Is In Range

I am checking if my number coming from a input field is in range function timeCheck(){ var time = $.trim($('#enterTime').value()); Number.prototype.between =

Solution 1:

Not a closing bracket but a missing parenthesis:

if((time).between(1,9){

Should be:

if ((time).between(1,9)){

or

if (time.between(1,9)){

Solution 2:

Extending @Daniel's answer, there are two other errors: first, $('#enterTime').value() is not a valid jQuery function, should be $('#enterTime').val(). Second, you need to convert your value to type Number. Otherwise, you will be trying to access the between property of a string, which doesn't exist. The final code would be:

function timeCheck(){
    var time = new Number($.trim($('#enterTime').val()));
    Number.prototype.between = function(min,max){
        return this > min && this < max;
    };
    if(time.between(1,9)){
        alert("test");
    }
}

Solution 3:

FIDDLE Try the following code

function timeCheck(){
    var time = parseInt($.trim($('#enterTime').val()),10);
        Number.prototype.between = function(min,max){
            var num = parseInt(this,10);

            return num >= min && num <= max; 
        }
            if((time).between(1,9)){
                alert("test");
            }
}

The issue was with type conversion object time was not of type Number.

Hope it helps .....


Solution 4:

This question was already asked: here

Try the function I propose (in the mentioned post it was for PHP) that is valid for increasing or decreasing ranges and not limited to integers:

function between(n, a, b)
{
    var chk= false;
   if ((a==n)&&(b==n)){
      chk = true;
    }else{
      chk = (n-a)*(n-b)<0;
    }
    return chk;
}

The function TRUE if n is between a and b


Post a Comment for "Check If Number Is In Range"