For <input type="number">
element, maxlength
is not working. How can I restrict the maxlength
for that number element?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a way to play audio on a mobile browser w
- HTML form is not sending $_POST values
- implementing html5 drag and drop photos with knock
-
Why does the box-shadow property not apply to a
You can specify the
min
andmax
attributes, which will allow input only within a specific range.This only works for the spinner control buttons, however. Although the user may be able to type a number greater than the allowed
max
, the form will not submit.Screenshot taken from Chrome 15
You can use the HTML5
oninput
event in JavaScript to limit the number of characters:As with
type="number"
, you specify amax
instead ofmaxlength
property, which is the maximum possible number possible. So with 4 digits,max
should be9999
, 5 digits99999
and so on.Also if you want to make sure it is a positive number, you could set
min="0"
, ensuring positive numbers.Another option is to just add a listener for anything with the maxlength attribute and add the slice value to that. Assuming the user doesn't want to use a function inside every event related to the input. Here's a code snippet. Ignore the CSS and HTML code, the JavaScript is what matters.
You can specify it as text, but add pettern, that match numbers only:
It works perfect and also on mobile ( tested on iOS 8 and Android ) pops out the number keyboard.
If you use "onkeypress" event then you will not get any user limitations as such while developing ( unit test it). And if you have requirement that do not allow user to enter after particular limit, take a look of this code and try once.
I had this problem before and I solved it using a combination of html5 number type and jQuery.
script:
I don't know if the events are a bit overkill but it solved my problem. JSfiddle