I am aware this question has been asked before (Use tab to indent in textarea), but the answers provided did not fix my problem. My code is as follows:
$(document).ready(() => {
document.getElementById('input').onkeydown = 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 jQuery solution doesn't work, either
$('#input').keydown(e => {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var start = this.selectionStart;
var end = this.selectionEnd;
// set textarea value to: text before caret + tab + text after caret
$(this).val($(this).val().substring(0, start)
+ "\t"
+ $(this).val().substring(end));
// put caret at right position again
this.selectionStart =
this.selectionEnd = start + 1;
}
});
*/
});
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>
<textarea id="input"></textarea>
</body>
</html>
Browser is Google Chrome 67 on a Mac.