Use tab to indent in textarea
Borrowing heavily from other answers for similar questions (posted below)...
document.getElementById('textbox').addEventListener('keydown', function(e) { if (e.key == 'Tab') { e.preventDefault(); var start = this.selectionStart; var end = this.selectionEnd; // set textarea value to: text before caret + tab + text after caret this.value = this.value.substring(0, start) + "\t" + this.value.substring(end); // put caret at right position again this.selectionStart = this.selectionEnd = start + 1; }});
<input type="text" name="test1" /><textarea id="textbox" name="test2"></textarea><input type="text" name="test3" />
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 solution does not require jQuery and will enable tab functionality on all textareas on a page.
As others have written, you can use JavaScript to capture the event, prevent the default action (so that the cursor does not shift focus) and insert a tab character.
But, disabling the default behavior makes it impossible to move the focus out of the text area without using a mouse. Blind users interact with web pages using the keyboard and nothing else -- they can't see the mouse pointer to do anything useful with it, so it's keyboard or nothing. The tab key is the primary way to navigate the document, and especially forms. Overriding the default behavior of the tab key will make it impossible for blind users to move the focus to the next form element.
So, if you're writing a web site for a broad audience, I'd recommend against doing this without a compelling reason, and provide some kind of alternative for blind users that doesn't trap them in the textarea.