Maximum Length in Textarea using jQuery

Posted: 11.4.2013

Enforcing a maximum character limit on a textarea is nothing ground breaking.  There are plenty of jQuery plugins that do it very well.  I wanted to dive into doing it myself to see learn more about it and how to implement it.  For this project I had two conditions for the functionality:

  1. Had to enforce maximum length of characters for textarea
  2. Had to not allow a user to paste in a text selection larger than the character limit

 

Attempt 1

    The first condition was an easy one to figure out and implement a solution for.  Below is the code.  What it does is bind to a keydown event in the textarea.  It checks the length of the textarea text against the character limit.  If it's greater than it then it cuts off the last letter.  But something interesting happens with this.  The limit is set at 15, but in Chrome (maybe others) you can type a 16th letter that will be appended to the text.  If I type another letter it will replace that 16th character and not append.  Strange behavior but not the biggest deal in the world.  With this solution condition 2 isn't met.  A user can paste in a large text selection and all of it will be posted.  Only when they press a key in the textarea will it chop off the portion that is too long. 

 

 

Attempt 2

    The second condition required a bit more work to figure out.  I couldn't just use the keydown jQuery event anymore because of what happened above.  I needed to catch the pasting event.  In the second attempt I change it to a .on event that is bount to three things: change, keydown, and paste.  The idea being that an event will fire on the paste event in the textarea.  Try it below by pasting in this code:   111111111111111copiedtext.  For it to work correctly you shouldn't be able to see the text 'copiedtext' but as you'll see, you will see that text until the textarea loses focus.  Again, condition 2 isn't met quite yet. 

 

 

Attempt 3

    After doing some digging I was finally able to find the solution.  Using the solution from attempt 2 I just needed to use a setTimeout call and have it set to zero.  From what others said it appears that by doing it that way the function call gets called very last.  Where as in attempt 2 it might have been running the function after I pasted it but before the text was in the textarea (or some other weird racing issue).  But by wrapping the length check function in a setTimout equal to 0 it works.  Not only does it meet condition 2 but condition 1 now works better as the weird 16th character issue doesn't happen.  

 

 

Conclusion

    In conclusion it was interesting to learn that by using a setTimeout of 0 that I was able to move the character length check to the bottom of the processing queue.  I'm not sure how often I will have a use of it but it is good to know.  Any questions, thoughts, or critiques?  Leave them below. 


Be Social


Share your thoughts


comments powered by Disqus