I wonder why default maxLength/minLength property for HTMLInputElement is set to -1 by default.
There is also confusing behavior like below:
- Example
<input type="text" />
const inputElement = document.querySelector('input');
console.log(inputElement.maxLength) // -1
- I set
maxLength
programatically
inputElement.maxLength = 2;
console.log(inputElement.maxLength) // 2
and html will reflect as
<input type="text" maxlength="2" />
- I remove
maxlength="2"
manually from devtools.
<input type="text" />
I get
console.log(inputElement.maxLength) // undefined
can someone tell me why is that? There is no such a thing in documentation, but i can see that every browser is pretty consistent in this.
[Edit] 3. is wrong in this example, it is return -1 https://stackoverflow.com/a/75541575/10465908
3
Answers
So answer to my original question is https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#limited-to-only-non-negative-numbers as
maxLength
is typelong
.But I discovered some interesting things during the investigation:
-1
but realmaxlength
is 524288, other engines seems not have this limitation.524288
in other browsers way back-1
Insightful question.
Well, according to the official docs of the Web, the World Wide Web,
And as we all know computers cannot represent infinity.
A big number (like 1 billion) is big but still not infinity or "unlimited". So the best way was to choose a negative number (-1). Just in this way, they are not setting a max length constraint on the input.
However, please note that they decided to do it just from their side (to do this workaround) i.e. we cannot set explicitly the -1. For example:
For the step 3 i’m getting
-1
when i remove attribute in chrome 110