You could use a number input <input type="number" min="0" max="100">
, but it won't work in all browsers so you'll have to complement it by some javascript in order to double check the value is correct.
restricting numbers to a percentage
-
03-06-2022 - |
Question
I was thinking about forcing people to be only capable of writing the numbers between 0-100 (because of the maximum number attained via a percentage is 100%).
Is there a way to force people to input a number between 0-100%? I am already restricting them to 3 digits using javascript.
I am looking to using javascript for this.
Solution
OTHER TIPS
You could use the Range type input element, which appears as a slider.
<input type="range" name="percentage" min="0" max="100">
Or you could run a validation function on the onchange or onkeyup events, that checks for a value more than 100.
<input type="text" name="percentage" onkeyup="validate(this);">
function validate(el){
if(el.value > 100){
el.value = 100;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow