How to catch TAB key press with JavaScript?

Dec 18, 2009 Posted by Lara Kannan
The example code is tested in IE, Firefox and Opare. Probably also works in Netscape as well as others like Safari.

<script type="text/javascript">
var obj;
var TAB = 9;
function catchTAB(evt,elem)
obj = elem;
var keyCode;
if ("which" in evt)
{// NN4 & FF &amp; Opera
} else if ("keyCode" in evt)
{// Safari & IE4+
} else if ("keyCode" in window.event)
{// IE4+
} else if ("which" in window.event)
} else { alert("the browser don't support"); }

if (keyCode == TAB)
obj.value = obj.value + "\t";
alert("TAB was pressed");
setTimeout("obj.focus()",1);// the focus is set back to the text input
<input type="text" onkeydown="catchTAB(event,this);">

Hope this will help you. Happy coding!
Labels: ,

Post a Comment