HTMLInputElement: maxLength 屬性
HTMLInputElement 介面的 maxLength 屬性表示允許在 <input> 元素的值中輸入的字元數(以 UTF-16 碼單元為單位)的最大值,也是允許該值有效的最大字元數。它反映了元素的 maxlength 屬性。-1 表示長度沒有限制。
注意:瀏覽器通常會阻止使用者輸入超過 maxlength 屬性允許的字元數。如果長度超過限制,該元素將被視為無效,並且 ValidityState 物件的 tooLong 屬性將為 true。
值
一個表示元素 maxlength 屬性值的數字,如果存在,否則為 -1。
示例
給定以下 HTML
html
<p>
<label for="password">Your password</label>
<input id="password" type="password" minlength="8" maxlength="20" />
</p>
您可以使用 maxLength 屬性來檢索或設定 <input> 的 maxlength 屬性值。
js
const inputElement = document.querySelector("#password");
console.log(`Element's maxLength: ${inputElement.maxLength}`); // "Element's maxlength: 20"
inputElement.maxLength = 18; // updates the element's maxlength attribute value
規範
| 規範 |
|---|
| HTML # dom-input-maxlength |
瀏覽器相容性
載入中…