LogoASPAlliance: Articles, reviews, and samples for .NET Developers
Tabbing in the TextArea
by Justin Lovell
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 20715/ 43

Sometimes we all need to insert a tab into a text area or a text box. In times past, we would have to create the tab character somewhere else, copy it to our clipboard, and instead of pressing the tab key, we would paste it from our clipboards. All of us are programmers and know that this breaks our flow very easily, but I have arrived at a better solution.

The JavaScript to do this is very simple. The only con of this approach is that it is an Internet Explorer 5+ trick, but here it is:

<script language="JavaScript">
function AllowTabCharacter() {
if (event != null) {
if (event.srcElement) {
if (event.srcElement.value) {
   if (event.keyCode == 9) { // tab character
if (document.selection != null) {

       document.selection.createRange().text = '\t';
       event.returnValue = false;
else {
event.srcElement.value += '\t';
return false;

The code ensures that the browser can support events at first. Then the code checks if the browser supports the W3C standards of the event model by checking if the element that caused the event to fire exists. It then checks if the element is a input field or text area. From there it checks the key code that fired the event. The Unicode key code for the tab character is "9."

At this point, we test to see if the browser supports user selections in text. If the browser does, we then insert the tab character in the current place in the input field. If the browser does not support this, we append a tab character at the end of the input field.

To use the above code, here is some sample code:

<textarea onkeydown="AllowTabCharacter()"></textarea>

Happy Programming!

Product Spotlight
Product Spotlight 

©Copyright 1998-2020  |  Page Processed at 2020-06-03 3:52:22 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search