Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 213
fightstarr20 Avatar asked Nov 28 '22 07:11

fightstarr20


2 Answers

This function check if number n is between a and b

function isBetween(n, a, b) {
   return (n - a) * (n - b) <= 0
}
like image 144
Yukulélé Avatar answered Dec 07 '22 23:12

Yukulélé


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);
like image 21
Ja͢ck Avatar answered Dec 07 '22 22:12

Ja͢ck