Inside Technique : Add Maxlength Functionality to Textareas
As a developers responsible for creating web-based front ends to databases, I find the inconsistencies in input controls makes my life a little harder. The maxLength property of INPUT_text elements represent an easy means of limiting user input to a specified length. This is crucial for a variable length character field; however, for really large fields, an INPUT_text element does not provide a decent means of input. Unfortunately, TEXTAREA elements do not offer the same functionality. This failure of the DHTML object model can make your forms annoying to use. In this article, I will show you how to add a maxLength property to TEXTAREA elements with a re-usable HTML Component which makes the interface of the two elements work exactly the same.
If we examine the maxLength property of the INPUT_text element we see that it sets or retrieves the maximum number of characters that can be entered into a text control. The property limits the user entry, not programmatic assignments to the value property. The property's value can be larger than the size of the text box, in which case the text box scrolls as necessary as the user types.
Our goal in creating the HTC is to create the same type of limit to user input. To accomplish that task, we need to limit the number of keystrokes within the onkeypress event. We must also create a customized onpaste event handler such that the user cannot paste in more characters than the field should hold. Below is a form which provides the necessary maxLength limitations. Compare the performance of the INPUT_text and TEXTAREA elements. Try typing and pasting values into both fields (each has a maxlength of "50").
Now let's look at the behavior which handles this set of functionality.
Page 1:Add Maxlength Functionality to Textareas
© 1997-2000 InsideDHTML.com, LLC. All rights reserved.