fightstarr20
fightstarr20

Reputation: 12568

Check if number is between two numbers

I have a variable called 'age' and am trying to work out if it is between two numbers. In this case I want to find out if the age is between 30 and 80.

I have this so far...

if (age >= 30 && age <= 80) {
  $('.display').each(function () {
    $(this).css('display', '');
  });
}

This works great if the age is below 30 then the .display div does not get displayed, but the last part where it checks if the number is less than 80 does not work.

Can anyone point me in the direction of a similar function I can read up on? Or am I doing something obvious wrong?

Upvotes: 5

Views: 38890

Answers (5)

Ja͢ck
Ja͢ck

Reputation: 173542

The condition that you wrote to determine whether a value is in between two values is fine. What seems to be happening here is that once the condition of age >= 30 is reached, e.g. 31, the display attribute gets updated, but once it goes over 80, it doesn’t revert back any style changes.

Instead of modifying the display CSS property, in jQuery you would typically use the show and hide methods, such as .toggle():

// only show if age is between 30 and 80
$('.display').toggle(age >= 30 && age <=80);

Upvotes: 5

Yukul&#233;l&#233;
Yukul&#233;l&#233;

Reputation: 17062

This function check if number n is between a and b

function isBetween(n, a, b) {
   return (n - a) * (n - b) <= 0
}

Upvotes: 31

Luis Rosety
Luis Rosety

Reputation: 394

As I said in this post you can use a function similar to this one:

function between(n, a, b)
{
    return ((a==n)&&(b==n))? true : ($n-$a)*($n-$b)<0;
}

And it is not limited to integer numbers as other functions are.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

jQuery is weird.

In plain JavaScript:

this.style.display = "";

... will delete any display setting that has been made in JavaScript (or jQuery, or in raw HTML style="..." attribute), allowing the CSS-defined value (or default) to take over.

jQuery needs some kind of hack that I don't even remember right now to make it work... Not worth it IMO, when the JS is so simple.

Upvotes: -2

Rory McCrossan
Rory McCrossan

Reputation: 337560

'' isn't a correct setting for the display property. From what you describe, you want to use block. Also, you don't need to use an each() loop here. Try this:

if (age >= 30 && age <= 80) {
    $('.display').css('display', 'block');
}

Example fiddle

Upvotes: 3

Related Questions