I have an HTML page that has a textarea. I want to be able to use the tab button inside it instead of it switching focus. I included the code from this answer to another question, but the tab still switches focus. If I run that same code in my JavaScript console, however, it changes the behavior of the tab button to create a tab character.
The relevant code I tried is this:
$("textarea").keydown(function(e) {
if (e.keyCode === 9) { // tab was pressed
// get caret position/selection
var start = this.selectionStart;
var end = this.selectionEnd;
var $this = $(this);
var value = $this.val();
// set textarea value to: text before caret + tab + text after caret
$this.val(value.substring(0, start) + "\t" + value.substring(end));
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
// prevent the focus lose
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="20" cols="150"></textarea>