8

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">

2 Answers 2

11

There'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">

Sign up to request clarification or add additional context in comments.

7 Comments

Yes I was thinking to use this but I can type in a minus number like -1 and wouldn't be the minimum then
OK @Behar, fixed - try typing a number then pressing enter/return.
It still stays the same number when I type like -1, 0, etc so I am able to type negative numbers and less than 1 and greater than 50?
See my second snippet @Behar.
Your code didn't have JS code so that's why and now with JS tried and it works, thank you :) And a question about a negative number like -1, in your code I don't see any if statement for negative numbers like if I type -1 it automatically replaces to 1, so I think " if (v < 1) this.value = 1; if (v > 50) this.value = 50;" They compare for negative value right ?
|
7
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)> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.