Javascript: Limit Textarea

April 14, 2010 by JavaScript  

Limiting the amount of characters that a html textbox can take is quite straightforward, you simply add the maxlength attribute and thats it.

Unfortunately for some strange reason a html textarea doesn't have this attribute, hence the reason for this post.

We're going to attempt to add/process this attribute, like the following snippet:

<table>
	<tr>
		<td>
			Title
		</td>
		<td>
			<input name="txtTitle" type="text" maxlength="32">
		</td>
	</tr>
	<tr>
		<td>
			Description
		</td>
		<td>
			<textarea name="txtDescription" maxlength="128" rows="4" cols="40"></textarea>
		</td>
	</tr>
	<tr>
		<td>
			Body
		</td>
		<td>
			<textarea name="txtBody" maxlength="1024" rows="20" cols="80"></textarea>
		</td>
	</tr>			
</table>

You simply need to include the following script on your page, which loops through all the textareas on a page, searching for the maxlength attribute.
function limiter()
{
	var textareas = document.getElementsByTagName('textarea');
	
	for(var i = 0; i < textareas.length; i++)
	{
		var textarea = textareas.item(i);
		limit(textarea);
	}
}

function limit(sender)
{
	var maxlength = sender.getAttribute('maxlength');
	if (maxlength != null)
	{
		// limit input values
		sender.onkeypress = function(e)
		{					
			// Crossbrowser Issue 
			if (e == null)
				e = window.event;
			
			// exclude certain keys from our limiter
			if ((e.keyCode == 8) || 
				(e.keyCode > 36) && 
				(e.keyCode < 41)) return true;
				
			return (sender.value.length < maxlength);
		}
		
		// limit pasted values
		sender.onpaste = function()
		{
			// onAfterPaste
			setTimeout(function()
			{
				if(sender.value.length > maxlength) {
					sender.value = sender.value.substring(0, maxlength);
				}							
			}, 1);
		}
	}
}

// Only Attach events needed for limiting the textareas once the page finished loading
if (window.addEventListener) { // FF etc
	window.addEventListener('load', limiter, false);
}
else{ // IE
	window.attachEvent('onload', limiter);
}


Leave a Comment


August 31, 2010 by Anonymous

This was really helpful for me. Thanks a lot ! :)



    Related Downloads

    Set maximum length of a textbox