I have got a quick question

How can I limit a number input so the user can’t type any number but numbers from 0 to 100. I know I can do that with max and min but it only works on those arrows on the side of an input and the user still can just type bigger or smaller value.

So, I looked up the question and found this solution on stack overflow javascript - How to prevent inserting value that is greater than to max in number field in html - Stack Overflow

Here is a working codepen with the solution they provided here. The way it works is the max is set to 10 and if the user tries typing a number greater than the max then number will be set to the max. I have adjusted the codepen to make it 100 instead of 10 per your question.

1 Like

thank you sir it works but there is still an option of typing negative numbers and I’m trying to figure it out any suggestions?

Sorry if this is pointing out the blindingly obvious (and doesn’t address your issue) but, if you apply max and min to an HTML input, it won’t accept inputs which are outside of the specified range. You can type whatever you like but when you hit ‘Submit’, you’ll get a range error.

yeah I have noticed that but is there an option I can actually limit the input to some range?

I have updated the code pen to not allow negatives

I don’t know of a simple way (though I know little in the grand scheme of things) but you could perhaps hard-code an input element in such a way that it will refuse inputs outside of the range.

For instance, you could create a <div> element which, when it’s clicked on and typed in, could keep track of each keypress and update its contents accordingly, but refuse input when a particular keypress would mean that the input as a whole is out of range.

I think I found a way. it is to assign a value 100 when the value is bigger than a 100 and assign 0 when the value is smaller than zero

 $('input').on('input', function () {
    var value = this.value;
    if (value !== '') {
        value = parseFloat(value);
        if (value < 0)
            this.value = 0;
        else if (value > 100)
            this.value = 100;

thank you for help :slight_smile:

Yes, that would be a lot simpler than my suggestion :rofl:

1 Like

Just another tip. Do not use var. var is outdated, you want to use either const or let

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.