Use tab to indent in textarea

user780483 picture user780483 · Jul 9, 2011 · Viewed 114.3k times · Source

I have a simple html textarea on my side. Right now if you click tab in it, it goes to the next field. I would like to make the tab button indent a few spaces instead. How can I do this? Thanks.

Answer

kasdega picture kasdega · Jul 9, 2011

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" />

jQuery: How to capture the TAB keypress within a Textbox

How to handle <tab> in textarea?