Limiting the content of a TextArea

Being able to limit the length of the content entered into a TextArea can be useful for various reasons. Although not supported natively by HTML, you can achieve the same effect using Javascript - on KeyUp and KeyDown events, check the length of the textarea value and truncate if necessary. We can also display how many characters are remaining if we want to provide user feedback.

Because I've used this technique in several Grails applications, I've created a simple TagLib - you may want to customize it to your requirements.

To use it:

  • include the prototype library with <g:javascript library="prototype"/>

  • use <jttext:changeScript /> once on your page for the utility script

  • define your textarea including the maxlength attribute with <jttext:textArea id="messageField" maxlength="20" />

  • use <jttext:statusDiv for="messageField" /> to display the status message showing how many characters are left

So, a simple GSP would look like:

<g:javascript library="prototype"/>
<jttext:changeScript />


<jttext:textArea name="messageField" class="sized" style="width:320px;height:60px;" maxlength="20" />
<jttext:statusDiv for="messageField" />


Effectively what you get looks like this (the HTML code has been slightly modified to work in this post):


Download TagLib here.

Popular posts from this blog

Using the Crystal Reports Java API to generate PDF

No Scope registered for scope request

Using Selenium WebDriver to select JSF/PrimeFaces selectOneMenu options