How to use the Math.min() and Math.max() methods In Javascript
In this approach, we will use the Math.min() and Math.max() methods to limit theentered number.
Example: The below example illustrates the use of the Math.min() and Math.max() methods to limit the entered number.
html
<!DOCTYPE html> < html > < head > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" > </ script > </ head > < body > < h1 style = "color:green;" > w3wiki </ h1 > < p id = "GFG_UP" > </ p > Enter a Number: < input id = "num" /> < br > < br > < button onclick = "GFG_Fun();" > click here </ button > < p id = "GFG_DOWN" > </ p > < script > const up = document. getElementById('GFG_UP'); const down = document. getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to check if the types number " + "is in range or not.< br >Min Value - 0 < br > Max Value - 100"; function GFG_Fun() { const input = document. getElementById('num'); let n = input.value; n = Number(n); n = Math.min(100, Math.max(0, n)); $('#GFG_DOWN'). html('Number ranged to < br >N = ' + n); } </ script > </ body > </ html > |
Output:
How to limit a number between a min/max value in JavaScript ?
Given the HTML document. The task is to verify whether the input number is in the specified range or not while taking input a number from the user via the input element. If it is not then make it to lie within the range.
These are the two approaches:
Table of Content
- Using the if-else condition
- Using the Math.min() and Math.max() methods