I just wanted to know if we could get the maxlength of an input field from javascript

<input type="password" id="password" maxlength="20" >

I tried this but it returns undefined

console.log(document.getElementById("password").maxlength);
有帮助吗?

解决方案

document.getElementById("password").maxLength

To access it with Javascript you need an uppercase 'L'

W3 Schools Example

其他提示

Use DOMElement::getAttribute() to obtain properties, that not listed in DOMElement, but existing in markup:

var el = document.getElementById("password");
console.log(el.getAttribute('maxlength'));

The accepted answer is actually wrong:

document.getElementById("password").maxLength

Will get you the maxLength attribute e.g. maxLength="2", to get the value you must get just that:

document.getElementById("password").maxLength.value /* <-- note .value */
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top