Reputation: 10216
I need to insert a tab into a textarea when a tab is clicked rather than moving the focus to the next element.
I've done some research but found no solutions that actually use tab instead of a series of spaces.
How would I do this and how would I insert a true tab instead of 4 spaces?
Upvotes: 3
Views: 491
Reputation: 207919
JavaScript:
function insertTab(o, e) {
var kC = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which;
if (kC == 9 && !e.shiftKey && !e.ctrlKey && !e.altKey) {
var oS = o.scrollTop;
if (o.setSelectionRange) {
var sS = o.selectionStart;
var sE = o.selectionEnd;
o.value = o.value.substring(0, sS) + "\t" + o.value.substr(sE);
o.setSelectionRange(sS + 1, sS + 1);
o.focus();
}
else if (o.createTextRange) {
document.selection.createRange().text = "\t";
e.returnValue = false;
}
o.scrollTop = oS;
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
return true;
}
Ripped without shame from here.
Upvotes: 3
Reputation: 324690
Wherever the code says to add those four spaces, replace the four spaces either with a literal tab character, or with the escape sequence \t
.
Upvotes: 1