Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keypress in jQuery: Press TAB inside TEXTAREA (when editing an existing text)

I want to insert TAB characters inside a TEXTAREA, like this:

<textarea>{KEYPRESS-INSERTS-TAB-HERE}Hello World</textarea>

I can insert before/after the existing TEXTAREA text - and I can insert / replace all text in the TEXTAREA - but have not yet been able to insert inside the existing TEXTAREA text (by the cursor) in a simple way.

$('textarea:input').live('keypress', function(e) {
    if (e.keyCode == 9) {
        e.preventDefault();

        // Press TAB to append a string (keeps the original TEXTAREA text).
        $(this).append("TAB TAB TAB AFTER TEXTAREA TEXT");

        // Press TAB to append a string (keeps the original TEXTAREA text).
        $(this).focus().prepend("TAB TAB TAB BEFORE TEXTAREA TEXT");

        // Press TAB to replace a all text inside TEXTAREA.
        $(this).val("INSERT INTO TEXTAREA / REPLACE EXISTING TEXT");

    }
});

There is a "tabs in textarea" plug-in for jQuery ("Tabby") - but it's 254 code lines - I was hoping for just a few lines of code.

A few links that I studied: (again, I would prefer fewer code lines).

http://www.dynamicdrive.com/forums/showthread.php?t=34452
http://www.webdeveloper.com/forum/showthread.php?t=32317
http://pallieter.org/Projects/insertTab/

Please advise. Thanks.

like image 561
Kristoffer Bohmann Avatar asked Nov 15 '09 20:11

Kristoffer Bohmann


2 Answers

I was creating a AJAX powered simple IDE for myself so I can rapidly test out PHP snippets.

I remember stumbling upon the same problem, here's how I solved it:

$('#input').keypress(function (e) {
    if (e.keyCode == 9) {
        var myValue = "\t";
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos,this.value.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;

        e.preventDefault();
    }
});

#input is the ID of the textarea.

The code is not completely mine, I found it on Google somewhere.

I've only tested it on FF 3.5 and IE7. It does not work on IE7 sadly.

like image 84
Waleed Amjad Avatar answered Sep 23 '22 03:09

Waleed Amjad


Unfortunately, manipulating the text inside textarea elements is not as simple as one might hope. The reason that Tabby is larger than those simple snippets is that it works better. It has better cross-browser compatibility and handles things like tabbing selections.

When minified, it's only about 5k. I'd suggest using it. You'll either have to discover and troubleshoot those same edge cases yourself anyway, or might not even know about them if users don't report them.

like image 34
Dave Ward Avatar answered Sep 24 '22 03:09

Dave Ward