document.querySelector('#textarea').addEventListener('keydown', e => {
if ( e.key === 'Tab' && !e.shiftKey ) {
// execCommand operations are "Cmd|Ctrl+Z"-able
// note: execCommand is deprecated and may not work in the future
document.execCommand('insertText', false, " ");
e.preventDefault();
return false;
}
});
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) +
" " + this.value.substring(end);
// put caret at right position again
this.selectionStart =
this.selectionEnd = start + 1;
}
});
$(document).delegate('#textbox', 'keydown', function(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)
+ " "
+ $(this).val().substring(end));
// put caret at right position again
this.selectionStart =
this.selectionEnd = start + 1;
}
});