Pages

Monday, June 12, 2017

Detect when a user stops typing with jQuery

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 couldnt 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:

http://dl.dropbox.com/u/6217043/js-example/example.html

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:
http://dl.dropbox.com/u/6217043/js-example/onfinishinput.js

The script requires jQuery to function, the latest jQuery can be downloaded from here:
http://jquery.com/

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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.