Javascript: Limit Textarea



Source Code

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);
}
 








Comments



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


Post comment

Name *
Email
Title
Body *
Security Code
*
* Required fields

Latest Posts

Be the best stalker you can be


2011-12-13 22:33:54

Syntactic sugar (C#): Enum


2011-08-04 16:50:18

Top 5 posts

Simple WYSIWYG Editor


Creating a WYSIWYG textbox for your website is actually quite simple.
2007-02-01 12:00:00

Moving items between listboxes in ASP.net/PHP example


Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
2008-06-12 17:07:43

Cross Browser Issues: Firefox Word Wrapping


Firefox word wrapping issues
2008-06-09 09:51:21

Populate a TreeView Control C#


Populate a TreeView control in a windows application.
2009-08-27 16:01:03

C# YouTube : Google API


Post on how to integrate with YouTube using the Google Data API
2011-03-12 08:37:51