Monday, August 30, 2010

Detect when a user stops typing with jQuery

When writing forms I frequently find I need to do some of my validation server side(for example checking if a username is already taken) but want to have a responsive real-time field validation displayed to the user. Obviously this effect can be achieved using AJAX but if you want to validate while the user is typing sending an AJAX request on every keypress is a very inefficient way of doing things. It seems to me that a "onInputFinished" event is needed so that you can detect and take action when a user stops typing in an input field.

I had a bit of a google around and couldn't find an elegant solution for it so I decided to roll my own using jQuery. This simple jQuery script allow you to add the "onfinishinput" attribute to HTML input fields in the same way you would use normal onclick and onkeyup events.

you can check out a working example here:


Using the Script:
After including the script on your page you can use the new event like this:

<input type="text" onfinishinput="alert('You typed ' + input_field.val())" />

NOTE: instead of using "this" when referring to the element use "input_field" like the example above.

Installing the Script:
The script can be downloaded from here:

The script requires jQuery to function, the latest jQuery can be downloaded from here:

Just include the scripts on your page and you are ready to go.

4 comments:

  1. Wow this works perfect! Thanks for the function, I tested it on a textarea you just have to change input to text area and it works great.

    ReplyDelete
  2. Not quite perfect i'm afraid. It fails to detect copied entries.. so if i copy a text, it has no idea what happened. Care to fix? :)

    ReplyDelete