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:

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

<body>

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

</body>
</html>

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

Slow, Buffering, Stuttering Udemy Video

Intellij tip - Joining multiple lines into one

Looking for IT work in Australia? JobReel.com.au!