javascript 如何使用javascript获取输入字段的最大长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19120656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:27:05  来源:igfitidea点击:

how to get the maxlength of an input field using javascript

javascripthtmlmaxlength

提问by Tech Tech

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

我只是想知道我们是否可以从 javascript 中获取输入字段的最大长度

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

I tried this but it returns undefined

我试过了,但它返回 undefined

console.log(document.getElementById("password").maxlength);

回答by BlitZ

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

使用DOMElement::getAttribute()获得的属性,在一个DOMElement没有上市,但现有的标记:

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

回答by Tyler

document.getElementById("password").maxLength

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

要使用 Javascript 访问它,您需要一个大写的“L”

W3 Schools Example

W3 学校示例

回答by Darren Sweeney

The accepted answer is actually wrong:

接受的答案实际上是错误的:

document.getElementById("password").maxLength

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

将为您提供maxLength属性,例如maxLength="2",要获得您必须获得的值:

document.getElementById("password").maxLength.value /* <-- note .value */