HTML Input Max or Min Property Will Not Work If Users Type In Directly Into the Input Box
We can defince max or min property for input with type of number or date. The max or min property
will limit the range of input value when users click on the arrow on the right side of the input.
But the max or min propety won't work if users manually type in the inputs. Try use the arrow and type in
the below input to see result.
<input oninput = "showValue_1.innerHTML = this.value" type = "number" max =5 min = 0> <div id = "showValue_1"></div>
Solution
We can use some JavaScript to set the max or min value of an input.
<input max="5" oninput="getValue(this)" type="number" />
<div id="showValue_2"></div>
<script>
function getValue(t){
Remove 0 before any number.
//t.value = Number(t.value);
var value = t.value
var max = t.max;
var min = t.min;
//Add a Number method to value in the if statement, becaues value may be treated as a string.
if(Number(value)>max)t.value = max;
if(Number(value)<min)t.value = min;
showValue_2.innerHTML = t.value;
};
</script>
Solution Without Script Tag
<input max="5" oninput=" this.value = Number(this.value); this.value = Number(this.value) > this.max ? this.max : this.value; this.value = Number(this.value) < this.min ? this.min : this.value; showValue_3.innerHTML = this.value; " type="number" /> <div id="showValue_3"></div>
Key Points
I mentioned in this article that HTML inputs take input value as string even if it's set to be type number
This is the reason why we need to add convert input values to number with Number() method in the if statement.
We need to remove all 0s in front of all numbers with this.value = Number(this.value)
at the begining of each code block. Otherwise you will see numbers like 01, 02, 03, 04 or 05.
Comments
Post a Comment