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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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.