In PHP you can use this to keep a number between 2 values, minimum and maximum:
$n = min(max($n, 1), 20);
so if $n is larger than 20 it will take the value of 20. If it's smaller than 1 it will take the value of 1. Otherwise it will not change
How can I do this in javascript / jQuery ?
It's pretty much the same in JavaScript, only that min
and max
are members of the Math
object:
var n = Math.min(Math.max(n, 1), 20);
JavaScript has Math.min
[MDN] and Math.max
[MDN].
Alternatively, you can use the conditional operator:
n = n > 20 ? 20 : (n < 1 ? 1 : n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With