Home
 Index > JavaScript > How to set a maximum character length on a Text...

JavaScript:  TextArea

How to set a maximum character length on a TextArea field

Set a maximum character length on textareas with a character countdown to display to the user how many remaining characters can be entered.

Added on 18 Jun 2008

Scenarios:

Scenario Summary:
While setting maximum character lengths on textboxes is a no-brainer (i.e., maxlength="xx"), the maximum character length attribute is not available for textareas.
Scenario Details:

The objective is to set a maximum character length on the textarea, thus ensuring that the user's text input does not exceed the maximum allowable length. The end-user  should also see exactly how much more text he or she can enter at all times in order to make edits unnecessary when the end is reached.

Added on 18 Jun 2008

Solution Summary:
Add a character countdown function to the onpaste and onkeyup events of the TextArea.
Solution Details:

Add the following function to your JavaScript file:

function countDown(control, maxLen, counter, typeName) {
    
var len = control.value.length;
    
var txt = control.value;
    
var span = document.getElementById(counter);
     span.style.display = '';
     span.innerHTML = (maxLen - len) + ' characters remaining';
    
if (len >= (maxLen - 10)) {
          span.style.color = 'red';
         
if (len > maxLen) {
               control.innerHTML = txt.substring(0, maxLen);
               span.innerHTML = (maxLen - control.value.length) + ' characters remaining';
               alert(typeName + ' text exceeds the maximum allowed!');
          }
     } 
else {
          span.style.color = '';
     }
}

Modify your Multiline Textbox (ASP.NET Web Control) or TextArea as follows (including a new row for a label):

<TABLE>
   
<TR>
    
    <TD vAlign="top">Description:</TD>
    
    <TD>
    
        <asp:TextBox onpaste="countDown(this, 255, 'desc', 'Description');" id="Description" onkeyup="countDown(this, 255, 'desc', 'Description');"
    
                                   runat="server" TextMode="MultiLine"></asp:TextBox></TD>
   
</TR>
    
<TR>
    
    <TD vAlign="top"></TD>
    
    <TD><SPAN id="desc" style="DISPLAY: none">255 characters remaining</SPAN></TD>
   
</TR>
</TABLE>

The result should look as follows:
Description:

Was this solution useful? Yes No Added on 18 Jun 2008
Rating: 

Copyright 2010 © E-Centric, Inc. | Terms of Use