How can I capture tab key event and cancel default action of Tab key?

H

HopfZ

The default action of tab key is to move focus.
For example,
<textarea id="ta"></textarea>
<textarea id="tb"></textarea>

Pressing Tab key when cursor is in the first textarea results in cursor
in the second textarea.
Is there a cross-browser way to capture the event of pressing Tab key
in a textarea and canceling the focus-moving action?

I tried the following code:

<textarea id="ta"></textarea>
<textarea id="tb"></textarea>
<script>
document.getElementById('ta').onkeypress = function(e){
e = e || window.event;
var code = e.keyCode || e.which;
var c = String.fromCharCode(code);
if(c == '\t'){
alert('TAB pressed'); return false;
} else return true;
}
</script>

And I put cursor in the first textarea and pressed Tab.
IE 7 showed no alertbox and focus moved. not ok.
Firefox 2.0 showed alertbox and focus stayed. ok.
Opera 9 showed alertbox and focus moved. not ok.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top