jQuery Text Change Event
Simple cross browser detection of text changes for input and textarea elements using a jQuery custom event plugin by ZURB
See the blog post to view or add a comment »
Plugin Tested in FireFox (3, 3.5, 3.5, Win/OS X), Safari 4, Chrome 5, IE (6, 7, 8)
Real Time Validation
It's a common problem, you have a text form that you need to validate client side. It's easy enough to do this when the form is submitted but in some cases better to do as they type.
Imagine how annoying Twitter would be if you had to submit your tweet before it told you how many characters you had left. On the other hand this same immediate validation can be abused if overused. Don't insult the user by congratulating them for each and every text field they fill in.
Getting Down to Business
Enough theory, let's get down to implementation. Notice exhibit A to the right, looks like a standard textarea with a disabled save button. Witness the button enable when there is text in the field, and disable when there is not. Moderately impressive right?
Try copying, pasting, or cutting text with the shortcut keys. OK, try doing that with a right click or the edit menu. Pretty sweet huh? Try all those interactions on twitter.com (hint, they don't support the click or menu interactions).
Download and link up our textchange plugin.
The plugin adds the
notext events that you can bind input and textarea elements to.
hastext event fires when the element goes from having no text to having text, and the
notext event fires when the element goes from having text to being blank. Looking for more advanced validation? Keep reading.
Detecting Text Changes
There is a third
textchange event that fires whenever the text changes and provides you with the previous value. Give it a try over in Exhibit B.
Twitter Style Validation
We can implement some simple Twitter like validation with just a single line and our textchange event.
With a little more code and
setTimeout we can hookup an AJAX call to save a few seconds after the user stops editing.
The AJAX call is just stubbed out here but you get the idea.
This is a little contrived but maybe you need to ensure that the companion cube is in the emergency intelligence incinerator before allowing the user to continue.
Copyright ZURB, freely available for distribution under the MIT license.