For element,
maxlength
is not working. How can I restrict the maxlength
for that number element?
As I found out you cannot use any of onkeydown
, onkeypress
or onkeyup
events for a complete solution including mobile browsers. By the way onkeypress
is deprecated and not present anymore in chrome/opera for android (see: UI Events
W3C Working Draft, 04 August 2016).
I figured out a solution using the oninput
event only.
You may have to do additional number checking as required such as negative/positive sign or decimal and thousand separators and the like but as a start the following should suffice:
function checkMaxLength(event) {
// Prepare to restore the previous value.
if (this.oldValue === undefined) {
this.oldValue = this.defaultValue;
}
if (this.value.length > this.maxLength) {
// Set back to the previous value.
this.value = oldVal;
}
else {
// Store the previous value.
this.oldValue = this.value;
// Make additional checks for +/- or ./, etc.
// Also consider to combine 'maxlength'
// with 'min' and 'max' to prevent wrong submits.
}
}
I would also recommend to combine maxlength
with min
and max
to prevent wrong submits as stated above several times.