Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » js » Limit Textfield Input

Limit Textfield Input

DHTML textfield limiter that uses javascript in an unobstrusive manner. All code is seperated from the HTML.

First off lets look at the straightforward HTML file. We set up a form to hold our input fields, only the 'textarea' is used in this example.

Here is the Html File which has the form we will use.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
	"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<title>maxchars</title>
	<script type="text/javascript" src="maxchars.js"></script>
	<link type="text/css" rel="stylesheet" href="maxchars.css">
</head>
<body>
	<div id="wrapper">
		<form id="myform" action="submit.php">
			<p><label for="name">Name</label>
				<input type="text" name="name" id="name"></p>

			<p><label for="email">Email</label>
				<input type="text" name="email" id="email"></p>

			<p><label for="msg">Message</label>
				<textarea name="message" id="message" cols="50" 
					rows="8" maxlength="50"></textarea>
				<span id="limiter"></span></p>
		</form>
	</div>

</body>
</html>

The 'maxlength' attribute is deprecated, but for this example we will use it. :)

That is all there is to the HTML, next we begin working with the Javascript.

For this example we will 'wrap' the entire script into a master object, this is done to keep all variable self-contained and will not interfere with other scripts on the page.

Here is the Javacript in full for all those copy & paste people.

var maxChars = {
        // cross-browser event handling for IE5+, NS6 and Mozilla 
        // By Scott Andrew 
	addEvent: function(elm, evType, fn, useCapture) {
		if(elm.addEventListener) {
			elm.addEventListener(evType, fn, useCapture);
			return true;
		} else if(elm.attachEvent) {
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		} else {
			elm['on' + evType] = fn;
		}
	},

	attVal: function(element, attName) {
	  return parseInt(element.getAttribute(attName));
	},

	init: function() {
		if(!document.getElementsByTagName || !document.getElementById) {
			return;
		}
		
		maxChars.form = document.getElementById('myform');
		maxChars.textarea = document.getElementById('message');
		maxChars.maxlength = maxChars.attVal(maxChars.textarea, 'maxlength');
		maxChars.limit_span = document.getElementById('limiter');
		maxChars.limit_span.innerHTML = '<strong>' + maxChars.maxlength + '</strong>' 
			+ ' characters remaining.';
		
		maxChars.addEvent(maxChars.textarea, 'keyup', maxChars.countlimit, false);
	},

	countlimit: function(e) {
		var placeholder;
		var lengthleft = maxChars.maxlength - maxChars.textarea.value.length;

		if(e && e.target) {
			placeholder = e.target;
		}

		if(window.event && window.event.srcElement) {
			placeholder = window.event.srcElement;
		}

		if(!placeholder) {
			return;
		} else if(lengthleft < 0) {
			maxChars.textarea.value = maxChars.textarea.value
				.substring(0, maxChars.maxlength);
		} else if(lengthleft > 1) {
			maxChars.limit_span.innerHTML = '<strong>' + lengthleft + '</strong>' 
				+ ' characters remaining.';
		} else {
			maxChars.limit_span.innerHTML = '<strong>' + lengthleft + '</strong>' 
				+ ' character remaining.';
		}
	}

}

maxChars.addEvent(window, 'load', maxChars.init, false);

Now lets run through the code to get an understanding of how it works.

This is used to define the object and get things started

var maxChars = {

The initial function called when the page loads. Check to see if 'DOM' elements are available and if they aren't exit the script. We then grab the id of the form, textarea and span tag that display the remaining characters. The last step in this function is to set up a key listener event.

init: function() {
	if(!document.getElementsByTagName || !document.getElementById) {
		return;
	}
	
	maxChars.form = document.getElementById('myform');
	maxChars.textarea = document.getElementById('message');
	maxChars.maxlength = maxChars.attVal(maxChars.textarea, 'maxlength');
	maxChars.limit_span = document.getElementById('limiter');
	maxChars.limit_span.innerHTML = '<strong>' + maxChars.maxlength + '</strong>' 
		+ ' characters remaining.';
	
	maxChars.addEvent(maxChars.textarea, 'keyup', maxChars.countlimit, false);
},

For multiple browser support we will use a function to assign event listeners. IE uses on'eventname' where standards browsers use 'eventname'.

// cross-browser event handling for IE5+, NS6 and Mozilla 
// By Scott Andrew 
addEvent: function(elm, evType, fn, useCapture) {
	if(elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if(elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	} else {
		elm['on' + evType] = fn;
	}
},

This function will be used to get our 'deprecated' element later on in the script. It simply returns the value of the passed in element.

attVal: function(element, attName) {
  return parseInt(element.getAttribute(attName));
},

Our last function in this script is to count and return the remaining characters.

countlimit: function(e) {
	var placeholder;
	var lengthleft = maxChars.maxlength - maxChars.textarea.value.length;

Check to see if the element is available. We use the tertiary condition to simply check for the event in a cross-broswer manner.

	if(e && e.target) {
		placeholder = e.target;
	}

	if(window.event && window.event.srcElement) {
		placeholder = window.event.srcElement;
	}

Check to see if an event exists and if it does continue on with the rest of the script. If the remaining length is less than 0(zero) change the string to be grammatically correct

	if(!placeholder) {
		return;
	} else if(lengthleft < 0) {
		maxChars.textarea.value = maxChars.textarea.value
			.substring(0, maxChars.maxlength);
	} else if(lengthleft > 1) {
		maxChars.limit_span.innerHTML = '<strong>' + lengthleft 
			+ '</strong>' + ' characters remaining.';
	} else {
		maxChars.limit_span.innerHTML = '<strong>' + lengthleft 
			+ '</strong>' + ' character remaining.';
	}
}

Finally end the object

}

That is the end of the article and I hope you know understand how this works. If you have questions or comments just post in the comment panel found at the bottom of every article on Scriptplayground.

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Limit Textfield Input

 Cherries  Wed Aug 2, 2006 7:31 am  
this is soo much more complicated then it needs to be.
also this isn't really a tutorial, as you haven't explained any code.
 Matthew  Wed Aug 2, 2006 8:04 am  
I appreciate your comments but I "mkeefe" did not write this tutorial, it was submitted by a reader and only approved by the Scriptplayground team based on initial acceptance. If you feel it should be edited or removed please contact me.
 Rob  Mon Apr 21, 2008 4:38 am  
I'm a little late to the party here, but this page was near the top results for a google search so I'd hate for anyone to pick up bad habits from this page...

The author takes pride in having his JS code separated from his HTML, but the effort to make this separation has two purposes. One: by separating them your JS and HTML both become more readable. Two: it tends to force better code design by not relying on inlining code. Better design means that the code can be applied in several areas of the page instead of writing the inline code in each area.

This script fails on the second point since maxChars.init references elements by their IDs. This script only works for pages with one textarea called message. To apply this to multiple textareas you'd need to make a copy of this script for each textarea you have, or modify the script in other ways.

The script could be much more elegant. For example, it could have a single function that takes a reference to an element. The function adds the key listener that calls the length-limiting function. You could even have this function create the span that is used to display the count of remaining characters so that this script can seamlessly be integrated to existing pages by adding one line of JS per input field.
 mkeefe  Mon Apr 21, 2008 5:43 am  
That is some really good information for readers that would like to extend upon the script more easily. Once I get a moment I will incorporate your ideas and update the article.

Thanks again,
 Rob  Mon Apr 21, 2008 6:42 am  
Wow, that was a quicker response than I expected. Thanks!
 Brett  Mon Jul 26, 2010 8:50 am  
good code base... I have some suggestions, for the same reason Rob made suggestions in 2008. This article is among the top returned results in a simple google search 'javascript limit input'.

I suggest wrapping maxChars in a function with passing parameters: the element id/name and maxlength. I really don't see the point specifing the form by your example. Theres no need in using the maxlength attribute in this manner, so you can apply your code to any text input control.

I also recommend using a name convention for the 'limiter' spans, such as the element id/name + "_limiter", in order to use the obj.limiter_span assignment more programmatic/dynamic.

you should now be able to call the function(el,int) and it will handle your code/functions appropriately.
Add a comment
The ability to add new comments has been disabled in this archived version.

Loading
Main | Tutorials | Articles