Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use JavaScript to limit a number between a min/max value?

I want to limit a number between two values, I know that in PHP you can do this:

$number = min(max(intval($number), 1), 20); // this will make $number 1 if it's lower than 1, and 20 if it's higher than 20 

How can I do this in javascript, without having to write multiple if statements and stuff like that? Thanks.

like image 710
Alexandra Avatar asked Apr 30 '11 15:04

Alexandra


People also ask

Which value is any number between minimum and maximum?

The range is a numerical indication of the span of our data. To calculate a range, simply subtract the min (13) from the max (110).

How do you set the maximum and minimum value of an input type text?

addEventListener('change', function(e) { var num = parseInt(this. value, 10), min = 0, max = 100; if (isNaN(num)) { this. value = ""; return; } this.

Does JavaScript have a max function?

max() function in JavaScript. The max() function of the Math object accepts multiple numbers and returns the largest numbers among them. And, if you do not pass any arguments to it will return infinity.


1 Answers

like this

var number = Math.min(Math.max(parseInt(number), 1), 20); 

Live Demo:

function limitNumberWithinRange(num, min, max){    const MIN = min || 1;    const MAX = max || 20;    const parsed = parseInt(num)    return Math.min(Math.max(parsed, MIN), MAX)  }    alert(    limitNumberWithinRange(  prompt("enter a number")   )  )
like image 170
Govind Malviya Avatar answered Oct 15 '22 13:10

Govind Malviya