Call Custom functions on Tab KeyPress in TextBoxes using jQuery

I was recently asked how to cancel Tab Key on a TextBox and instead call a custom function using jQuery. Here’s the code for it:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Call Custom functions on Tab KeyPress in TextBoxes</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$('input.tabcancel').bind('keydown', function(e) {
var keyCode = e.keyCode e.which;
if (keyCode == 9) {
e.preventDefault();
alertMe();
}
});
});

function alertMe() {
var $par = $("#para");
$par.html('perform some action here');
setTimeout(function() {
$par.empty();
}, 1000);

}
</script>
</
head>
<
body>
<
input type="text" class="tabcancel" /><br />
<
input type="text" class="tabcancel" /><br />
<
input type="text" /><br />
<
input type="text" class="tabcancel" /><br />
<
p id="para"/>
</
body>
</
html>



The code shown above handles the keydown event on all textboxes with the class ‘tabcancel’. The keyCode == 9 determines the tab key and we cancel the tab using e.preventDefault() and call a custom function alertMe(). The setTimeout() empties the contents of the para after 1 second.

See a Live Demo



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

Anonymous said...

Not very good, I mean, yes it's nice but, when you've typed in something you can't tab further on to the next textbox which is bad.