Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  13] [ 2]  / answers: 1 / hits: 19407  / 10 Years ago, sat, september 13, 2014, 12:00:00

How can I stop user from adding number greater than max value and smaller then min value in html input(type = number)



<input id=ageRange type=number min=20 max= 50 maxlength=2></input>


I tried one javascript code, but it makes change after we add the value then it changes the value. Is there any way that I can stop user to put value in range or just there is no flickering in the input cell while we change value programatically?


More From » html

 Answers
30

You would need handle input at a low level and perform your own checks. To prevent the user from typing value larger than the maximum, you could handle the keypress event and then check the input character and whether it would make the value too large:



<input id=ageRange type=number min=20 max= 50 maxlength=2>
<script>
document.getElementById('ageRange').onkeypress =
function (e) {
var ev = e || window.event;
if(ev.charCode < 48 || ev.charCode > 57) {
return false; // not a digit
} else if(this.value * 10 + ev.charCode - 48 > this.max) {
return false;
} else {
return true;
}
}
</script>


This does prevent the user from inserting a larger value by pasting.



To prevent the user from deleting characters so that the value becomes too small, you would need to handle the rubout key, which is more problematic due to keyboard differences. But it would be poor usability. Suppose the user typed 30, then realized he meant to type 40. A code that prevents changing the value to too small would prevent removing either digit!



Browsers are expected to have their own user interface for <input type=number>, and this is the reason for using it. The interface is not meant to prevent the user from typing too large values but to detect them and report them so that the user can correct them. Before trying to substantially modify this, consider the potential confusion. If you do add code that prevents out-of-ranfe values, browsers will not show diagnostic messages (e.g. “Number must be less than or equal to 50”), as they do by default if they support <input type=number>, so your JavaScript code should probably issue its own diagnostics.


[#69466] Thursday, September 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anitamaeg

Total Points: 466
Total Questions: 106
Total Answers: 106

Location: Suriname
Member since Sun, Jun 13, 2021
3 Years ago
;