Limit the number of textarea input words

Source: Internet
Author: User

Today, the first requirement to receive a task is to limit the number of words, to see the previous code left by the predecessor, using textarea, so take it for granted maxlength, the results found useless. Check that the original textarea for maxlength support to Ie10, the customer just ask the development environment is IE8 ... Had to look for ways again.

The main problem here is not only to limit the keyboard input, but also to limit the copy and paste. The best way to do this is to eject the box when the user exceeds the limit, and force the input characters in the range to be taken. This can be better to achieve the front-end user requirements, for future database processing is more convenient.

Originally thought is to use key correlation method to detect, concrete method writing is very simple:

 1  <script>2  function   Limittextarea (field) { 3  maxlimit = 4000;  4  if  (field.value.length > Maxlimit) { 5  field.value = field.value.substring (0, maxlimit);  6  alert ("No more than 4000 words!") " 7   8
         9  </script> 
1 <textarea id= "Mqone" name= "Mqone" cols= "Ten" rows= "5" style= "width:200px" onkeydown= "Limittextarea (This) "Onkeyup=" Limittextarea (This) "onkeypress=" Limittextarea (This) "></textarea>

But it turns out that this method is not detectable for mouse operation, but it is possible for Ctrl + V. Finally, the Onpropertychange method is used:

style= "width:200px" onpropertychange= "Limittextarea (This)" ></textarea>

But this is also the IE proprietary method, FF and the like can use Oninput method, using the same method:

style= "width:200px" oninput= "Limittextarea (This)" ></textarea>

If you use browser detection can be separated, if there is no two attributes can be written together at the same time, no problem found.

Limit the number of textarea input words

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.