This article mainly introduces the strange performance of maxlength attributes in textarea. For more information, see html5, this attribute can limit the maximum number of characters entered in the input box. more conveniently, the pasted content can be automatically truncated based on the number of characters.
Recently, this requirement was met. Users can enter up to 600 characters (Chinese characters and letters are not differentiated), and the pasted content must be automatically truncated. After Entering 600 words, users cannot enter the content.
The first time I thought of maxlength, it basically met the needs, but there was still some weird performance.
See the following code:
/600
text.oninput = function() { already.textContent = text.value.length;}
In the above Code, the number of input characters is limited to 600, and the oninput is used to listen to user input, keydown is not used, because keydown can only listen to user keyboard input, and does not respond to pasting... Oninput can be used.
At this time, after entering 600 words directly, you can no longer enter, delete some, and then enter some, which is normal. It is strange that if you paste a lot of text into textarea and think that maxlength is automatically truncated, there are exactly 600 characters in textarea. At this time, you delete some characters and then try to input them again, you will find:
Enter a slot !!! If you want to delete more files, you can enter more files, !!! When the number of characters entered is less than 600 characters, it suddenly cannot be entered !!!
In chrome and on my android devices .. I do not know why. If input is tested, this will not happen, and if the value of the maxlength attribute is smaller, this will not happen, for example, 10...
In this case, maxlength is unreliable. Write more code on your own. Since oninput is so flexible, use it.
Modify the code, remove the maxlength attribute of textarea, and use input to listen to the value of textarea. If the value exceeds 600, it is automatically truncated, resulting in the illusion that the input cannot be entered.
text.oninput = function() { if(text.value.length >= 600) { text.value = text.value.substr(0,600); } already.textContent = text.value.length;}
If you are not at ease, you can continue to listen to the keydown event and stop the default event after entering more than 600 characters. However, there are several keys that cannot be banned: Delete the return and press Enter:
Text. onkeydown = function () {if (text. value. length> = 600) {// Delete: 46 Return: 8 press Enter: 13 if (! (E. which = '46' | e. which = '8' | e. which = '13') {e. preventDefault ();}}}
IE8 or lower does not support the maxlength attribute or oninput, but they have a more powerful method: onpropertychange.
The following code explains how textarea implements the maxlength attribute.