SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Add Maxlength Functionality to Textareas
By Matthew Frank

The following listing shows the file maxlength.htc.

<PUBLIC:COMPONENT id="bhvMaxlength" urn="maf:Maxlength">
	<PUBLIC:PROPERTY name="maxLength" />
	<PUBLIC:ATTACH event="onkeypress" handler="doKeypress" />
	<PUBLIC:ATTACH event="onbeforepaste" handler="doBeforePaste" />
	<PUBLIC:ATTACH event="onpaste" handler="doPaste" />

<SCRIPT language="JScript">
// Keep user from entering more than maxLength characters
function doKeypress(){
	if(maxLength && value.length > maxLength-1){
		event.returnValue = false;
		maxLength = parseInt(maxLength);
	}
}
// Cancel default behavior
function doBeforePaste(){
	if(maxLength)
		event.returnValue = false;
}
// Cancel default behavior and create a new paste routine
function doPaste(){
	if(maxLength){
		event.returnValue = false;
		maxLength = parseInt(maxLength);
		var oTR = element.document.selection.createRange();
		var iInsertLength = maxLength - value.length + oTR.text.length;
		var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
		oTR.text = sData;
	}
}
</SCRIPT>

</PUBLIC:COMPONENT>

As you can glean from the XML above, this component creates the maxLength property and attaches handlers to the onkeypress, onbeforepaste and onpaste events. Notice that the property is spelled as "maxLength". The spelling is used verbatim inside script; since the property is spelled as such for a textbox, I use the same spelling here in order to maintain consistency.

The onkeypress handler cancels any key stroke which would go over the limit. Cancelling the default action of the onbeforepaste and onpaste events prevents the browser from performing its own paste; a returnValue of false is necessary if you want to write your own paste routine. The paste routine above creates a TextRange object from the current selection in the document and replaces it with the clipboard data modified to fit within the maxLength constraint.

To apply this behavior to your forms, download the HTC file to your server (I always prefer to have one common directory for all of my behaviors) and add the following to your stylesheets:

TEXTAREA { behavior: url(/behaviors/maxlength.htc)}

Page 1:Add Maxlength Functionality to Textareas
Page 2:The MaxLength htc