TAB inside input boxes

When you want to insert a TAB character inside a textarea (or a textbox) in a web page, you press TAB key and the focus moves to another field in the page instead of a TAB character being inserted into the textarea. The problem is that TAB key is reserved for web pages to navigate through the objects that can be focused (or blurred) inside the web page.

TAB characters are especially useful when you want to display formatted text in your HTML text field. In order to solve this problem, we need to override one of onkey related events of the text field so that the TAB character would be inserted where the cursor stays instead of the text field losing the focus to the next control in the web page. There are three onkey related events: onkeydown, onkeyup and onkeypress for an HTML text field. However, onkeypress only fires for some special character set and it does not fire for the TAB key. Therefore, we can only use onkeydown or onkeyup. We will use onkeydown event since it fires as soon as the user presses a key, not when the user releases a key.

Define onkeydown event for the asp:textbox controls in <BODY> section of your ASPX page as follows:

<asp:textbox id="TextBox1" runat="server" width="520px">
    Press TAB key to move the focus to the next field when the cursor is here...
</asp:textbox><br>
<asp:textbox id="TextBox2" runat="server" onkeydown="HandleKeyDown(this);" width="520px">
    Press TAB key to insert a tab character into this textbox when the cursor is here...
</asp:textbox><br>
<asp:textbox id="TextArea1" runat="server" onkeydown="HandleKeyDown(this);" width="520px" height="200px" textmode="MultiLine">
    Press TAB key to insert a tab character into this textarea when the cursor is here...
</asp:textbox>

Then, add the following JavaScript code into <HEAD> section of your ASPX page:

<script language="javascript">
//<!--
function HandleKeyDown(obj)
{
    var tabKeyCode = 9;
    if (event.keyCode == tabKeyCode && event.srcElement == obj)
    {
        obj.selection = document.selection.createRange();
        obj.selection.text = String.fromCharCode(tabKeyCode);
        event.returnValue = false;
    }
}
//-->
</script>

The above code will only work for IE browsers. You will need to handle the onkeydown event differently for other browsers.

Author Barrington Haynes

I have nothing more to say

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.