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.

Implementing this requires binding events to the keyup event, and a couple other events if you want to detect text changes on cut and paste. Even if you're a JavaScript god it's tedious to keeping writing this logic over and over again. Be smart and use the ZURB text change event plugin instead.

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 hastext and notext events that you can bind input and textarea elements to.

The 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.

140

AJAX Save

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.

Validate Text

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.

Startup playground

Log in with your ZURB ID

Log in with Google

Don't have a ZURB ID? Sign up

Forgot password?
×

Sign up for a ZURB ID

Sign up with Google

Already have a ZURB ID? Log in

×