Capturing TAB key in text box [closed] Capturing TAB key in text box [closed] javascript javascript

Capturing TAB key in text box [closed]


Even if you capture the keydown/keyup event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring.

In Firefox you can call the preventDefault() method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a preventDefault method on its event object that works in IE and FF.

<body><input type="text" id="myInput"><script type="text/javascript">    var myInput = document.getElementById("myInput");    if(myInput.addEventListener ) {        myInput.addEventListener('keydown',this.keyHandler,false);    } else if(myInput.attachEvent ) {        myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */    }    function keyHandler(e) {        var TABKEY = 9;        if(e.keyCode == TABKEY) {            this.value += "    ";            if(e.preventDefault) {                e.preventDefault();            }            return false;        }    }</script></body>


I'd rather tab indentation not work than breaking tabbing between form items.

If you want to indent to put in code in the Markdown box, use Ctrl+K (or ⌘K on a Mac).

In terms of actually stopping the action, jQuery (which Stack Overflow uses) will stop an event from bubbling when you return false from an event callback. This makes life easier for working with multiple browsers.


The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:

document.onkeydown = TabExample;function TabExample(evt) {  var evt = (evt) ? evt : ((event) ? event : null);  var tabKey = 9;  if(evt.keyCode == tabKey) {    // do work  }}