Below is an input number form and with JavaScript, I have added some line of codes with the minimum number that can be written is 1 and the maximum number to be written would be 50. And when someone would try to type any number less than 1 and greater than 50 it would automatically replace it with number 1 or 50 but I'm not having success achieving this and I need your help.
document.getElementById('info1').addEventListener("input", function () {
let num = +this.value, max = 50, min = 1;
if (num > max || num < min) {
return false;
}
})
<input type="number" id="info1" size="4">
Below is an input number form and with JavaScript, I have added some line of codes with the minimum number that can be written is 1 and the maximum number to be written would be 50. And when someone would try to type any number less than 1 and greater than 50 it would automatically replace it with number 1 or 50 but I'm not having success achieving this and I need your help.
document.getElementById('info1').addEventListener("input", function () {
let num = +this.value, max = 50, min = 1;
if (num > max || num < min) {
return false;
}
})
<input type="number" id="info1" size="4">
Share
Improve this question
edited Jun 22, 2019 at 21:29
Jack Bashford
44.1k11 gold badges55 silver badges82 bronze badges
asked Jun 22, 2019 at 21:01
BeharBehar
1791 gold badge3 silver badges14 bronze badges
2 Answers
Reset to default 9There's already a HTML attribute pair for this exact purpose - min
and max
:
<input type="number" min="1" max="50">
If you also want this to occur when a user enters a number outside of the range:
document.getElementById("inp").addEventListener("change", function() {
let v = parseInt(this.value);
if (v < 1) this.value = 1;
if (v > 50) this.value = 50;
});
<input type="number" min="1" max="50" id="inp">
function imposeMinMax(el){
if(el.value != ""){
if(parseInt(el.value) < parseInt(el.min)){
el.value = el.min;
}
if(parseInt(el.value) > parseInt(el.max)){
el.value = el.max;
}
}
}
<input type=number min=1 max=50 onkeyup=imposeMinMax(this)>