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

1 comment:

  1. 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.

    ReplyDelete