Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript min max

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 ?

like image 954
Alex Avatar asked Nov 05 '11 13:11

Alex


2 Answers

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);
like image 188
Tim Cooper Avatar answered Oct 05 '22 09:10

Tim Cooper


JavaScript has Math.min [MDN] and Math.max [MDN].

Alternatively, you can use the conditional operator:

n = n > 20 ? 20 : (n < 1 ? 1 : n)
like image 32
Felix Kling Avatar answered Oct 05 '22 07:10

Felix Kling