Coder Perfect

To indent in a textarea, use the tab key.

Problem

On my website, I have a simple HTML textarea.

It now moves to the next field when you press Tab. Instead, I’d like the tab button to indent a few spaces.

I’m not sure how I’m going to accomplish it.

Asked by user780483

Solution #1

Taking a lot of cues from other people’s responses to comparable questions (posted below)…

How to capture the TAB keypress in a Textbox using jQuery

What is the best way to handle a tab> in a textarea?

Answered by kasdega

Solution #2

var textareas = document.getElementsByTagName('textarea');
var count = textareas.length;
for(var i=0;i<count;i++){
    textareas[i].onkeydown = function(e){
        if(e.keyCode==9 || e.which==9){
            e.preventDefault();
            var s = this.selectionStart;
            this.value = this.value.substring(0,this.selectionStart) + "\t" + this.value.substring(this.selectionEnd);
            this.selectionEnd = s+1; 
        }
    }
}

This approach does not use jQuery and provides tab capability to all textareas on a page.

Answered by user1949974

Solution #3

You can use JavaScript to catch the event, prohibit the default action (so that the cursor does not shift focus), and insert a tab character, as others have suggested.

However, removing the default behavior makes moving the focus off of the text box difficult without the use of a mouse. Users who are blind interact with websites solely through the keyboard; they can’t see the mouse pointer to do anything helpful with it, therefore it’s keyboard or nothing. The tab key is the most common way to navigate a document, particularly forms. By overriding the tab key’s default behavior, blind users will be unable to switch the attention to the next form element.

So, if you’re developing a website for a broad audience, I’d advise against doing this unless there’s a compelling reason, and instead give a way for blind people to avoid being trapped in the textarea.

Answered by Will Martin

Solution #4

For what it’s worth, here’s my one-liner in response to everything you’ve been discussing in this thread:

The latest versions of Chrome, Firefox, Internet Explorer, and Edge were used to perform the tests.

Answered by elgholm

Solution #5

Here’s my take on it, with the following additions:

Answered by Brad Robinson

Post is based on https://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea