3

I am checking if my number coming from a input field is in range

function timeCheck(){

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

But somehow it does not work .. the alert is never triggered

Thanks for help and fast answer

TamoDaleko
  • 151
  • 1
  • 12

4 Answers4

2

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)){
1

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 .....

Mayank
  • 1,351
  • 5
  • 23
  • 42
1

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");
    }
}
LostMyGlasses
  • 3,074
  • 20
  • 28
0

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

Community
  • 1
  • 1
Luis Rosety
  • 396
  • 4
  • 10