I have a textbox in a form, and I would like to set the maximum allowed number value to be 50. Is this possible with HTML? Thanks
-
1Possible duplicate: http://stackoverflow.com/questions/798250/jquery-validation-field-by-range or http://stackoverflow.com/questions/11121227/javascript-jquery-validate-input-with-a-number-range – MikeSmithDev Jan 22 '13 at 21:12
5 Answers
Yes. Use maxlength attribute.
<input type="text" size="10" maxlength="50">
EDIT: I misunderstood your question. If you want it so that the max number is 50 and it accepts nothing else you should just check the value that is accepted in the input and if it is greater than 50, you can do something (clear the textbox, throw an error, apply an error class, etc). Maybe write a function to tell if it is a number and is <= 50?
function isValidNum(n) {
if (!isNaN(parseFloat(n)) && isFinite(n) && n<=50)
//do something
}
From HERE
-
-
The user can't enter more than 50 characters if maxlength is set to 50. – Daniel Hedberg Jan 22 '13 at 21:13
-
No, I mean if the user types "51" into the box, I want the highest number possible to be 50, not 50 characters. – William L. Jan 22 '13 at 21:14
I think you are looking for the maxlength attribute:
<input type="text" maxlength="10">

- 5,677
- 4
- 36
- 61
you could do it with javascript on the onblur event
function txtOnBlur(txt){
if (txt.value >50){
txt.value = "";
alert("No values over 50");
}
}
add add the onBlur="javascript:txtOnBlur(this);" attribute to your textbox.
If it's the char lenght, just add teh maxlenght attribute (maxlength="50").

- 225
- 3
- 12
As far as I understand, what you are looking for is more like this: Limit input box to 0-100
Crimson has submitted an answer that sounds exactly as the code you need. Edited and refined for your need, it will become:
<script>
function handleChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 50) input.value = 50;
}
</script>
And your textbox would look something like this:
<input type="text" onChange="handleChange(this)" />
You want this:
<input type="number" min="1" max="50" />
Thus 51 is too high. 50 is okay. This is a HTML5 attribute.
Maxlengh
will allow 50 characters aka a number with 49 zeros after it. Which I don't think was what you mean.
Max
will allow the input to have a value of no higher than specified.
You will still need to validate it server side how ever.

- 8,135
- 17
- 83
- 146