Home Web Front-end JS Tutorial Detailed explanation of the strange behavior of maxlength attribute in textarea_javascript skills

Detailed explanation of the strange behavior of maxlength attribute in textarea_javascript skills

May 16, 2016 pm 03:23 PM

HTML5 has brought many changes to forms, such as maxlength, which we are going to talk about today. This attribute can limit the maximum number of characters entered in the input box. What is more convenient is that the pasted content can also be automatically truncated based on the number of characters.

I recently received a request to limit users to input a maximum of 600 characters (Chinese characters and letters are not distinguished), and the pasted content must also be automatically truncated. After 600 characters are entered, input cannot be made.

The first thing I thought of was maxlength, which basically meets the needs, but there are still some weird behaviors.

Look at the code below:

<textarea name="text" id="text" maxlength="600"></textarea>
<p><span id="already"></span>/<span>600</span></p>
text.oninput = function() {
  already.textContent = text.value.length;
}
Copy after login

The above code limits the number of input characters to 600 and monitors user input through oninput. Keydown is not used because keydown can only monitor user keyboard input and has no response to pasting. . . oninput can do it.

At this time, after entering 600 words directly, you can no longer enter. Delete some and enter some again, and the performance will be normal. The strange thing is that if you paste a lot of text into a textarea, it will be automatically truncated because of the existence of maxlength. At this time, there are exactly 600 characters in the textarea. At this time, if you delete some characters and then try to input again, you will find:

Holy shit, I can’t type! ! ! Delete more and you can continue typing, but! ! ! When I entered less than 600 characters, I suddenly couldn’t enter again! ! !

This happens under chrome and my android machine. . The reason is not known yet. After testing the input, this situation will not occur, and if the value of the maxlength attribute is smaller, this situation will not occur, such as 10. . .

In this case, maxlength is unreliable. Just write more code yourself. Since oninput is so flexible, use it.

Modify the code, remove the maxlength attribute of textarea, and use input to monitor the value of textarea. If it exceeds 600, it will be automatically truncated, creating the illusion that input is impossible.

text.oninput = function() {
  if(text.value.length >= 600) {
    text.value = text.value.substr(0,600);
  }
  already.textContent = text.value.length;
}
Copy after login

If you are not worried, you can continue to monitor the keydown event and prevent the default event after inputting more than 600 characters, but there are several keys that cannot be prohibited: delete backspace and carriage return:

text.onkeydown = function() {
  if(text.value.length >= 600) {
    // 删除:46 退格:8 回车:13
    if (!(e.which == '46' || e.which == '8' || e.which == '13')) {
      e.preventDefault();
    }
   }
}
Copy after login

IE8 and below do not support the maxlength attribute nor oninput, but they have a more powerful method: onpropertychange.

The following explains how textarea implements the maxlength attribute through one end of the code

<script language="javascript" type="text/javascript"> 
function textlen(x,y){ 
 var thelength = x.value.length; 
 window.status=thelength+' of '+y+' maximum characters.'; 
} 
function maxtext(x,y){ 
 tempstr = x.value 
 if(tempstr.length>y){ 
  x.value = tempstr.substring(0,y); 
 } 
 textlen(x,y); 
} 
</script> 
<form name="myform"> 
   <textarea name="mytextarea"  
              cols="45"  
              rows="3"  
              wrap="virtual"  
              onkeypress="return(this.value.length<20)" 
              onkeydown="textlen(this,20)"  
              onkeyup="textlen(this,20)"  
              onblur="maxtext(this,20)">
   </textarea> 
</form> 
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

jQuery Matrix Effects jQuery Matrix Effects Mar 10, 2025 am 12:52 AM

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of ​​the picture and uses jQuery to calculate the average color of each area. Then, use

10 Ways to Instantly Increase Your jQuery Performance 10 Ways to Instantly Increase Your jQuery Performance Mar 11, 2025 am 12:15 AM

This article outlines ten simple steps to significantly boost your script's performance. These techniques are straightforward and applicable to all skill levels. Stay Updated: Utilize a package manager like NPM with a bundler such as Vite to ensure

How to Build a Simple jQuery Slider How to Build a Simple jQuery Slider Mar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Enhancing Structural Markup with JavaScript Enhancing Structural Markup with JavaScript Mar 10, 2025 am 12:18 AM

Key Points Enhanced structured tagging with JavaScript can significantly improve the accessibility and maintainability of web page content while reducing file size. JavaScript can be effectively used to dynamically add functionality to HTML elements, such as using the cite attribute to automatically insert reference links into block references. Integrating JavaScript with structured tags allows you to create dynamic user interfaces, such as tab panels that do not require page refresh. It is crucial to ensure that JavaScript enhancements do not hinder the basic functionality of web pages; even if JavaScript is disabled, the page should remain functional. Advanced JavaScript technology can be used (

See all articles