.NET Tips and Tricks

Blog archive

Catching Every Keystroke with jQuery

In an earlier column I used the jQuery change function to wire up a function to run after a user makes a change to an entry in a textbox. That "after" is important because the function I wired up won't run when the user makes a change in a textbox -- the event waits until the user leaves the textbox before firing.

In that article I mentioned, in passing, that if you really did want to catch a change as soon as a user makes it, you want to wire up the oninput event: The oninput event really does fire as soon as the user makes any change in a textbox. The major issue with oninput is that it's only available in browsers that support that portion of the HTML5 specification.

Unlike many other HTML events there's no built-in jQuery function to pick up the oninput event, so you need to use the jQuery on function to wire up a function to the event.

Here's some code that wires up a function that displays an alert box as soon as the user makes a change:

$(":text").on("input", function () { alert("got it"); });

You'll notice in my code that I'm using the :text selector, which only wires my function up to textboxes (it doesn't attach other input elements like passwords or checkboxes and also ignores dropdown lists and textareas). Several of the elements I'm skipping don't need the oninput event because the jQuery change event fires as soon as the user makes a change: Checkboxes and dropdown lists fall into that group. Password textboxes and textareas don't get caught by the :text selector, however, so you'll need to use more selectors to catch events immediately with them.

Posted by Peter Vogel on 10/13/2015


comments powered by Disqus

Featured

Subscribe on YouTube