Max Hudson
Max Hudson

Reputation: 10216

Handle tab in textarea

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

Answers (2)

j08691
j08691

Reputation: 207919

jsFiddle example.

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

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions