Link to home
Start Free TrialLog in
Avatar of dshrenik
dshrenikFlag for United States of America

asked on

Return key pressed inside a text box must maintain no of TABs in the previous line

The attached code changes the behavior of the TAB key inside a text box, so that pressing the TAB key produces an indent, as opposed to changing focus. (I have added the following attribute to the textbox:
onkeydown="return interceptTabs(event, this);")

Now, when I hit the return key in a text box, the indent should be set to the same number of TABs as to what is now in the previous line.

Please tell me how this can be done.
function insertAtCursor(myField, myValue) {
        //IE support
        if (document.selection) {
            myField.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
        }

        //MOZILLA/NETSCAPE support
        else if (myField.selectionStart || myField.selectionStart == '0') {
            var startPos = myField.selectionStart;
            var endPos = myField.selectionEnd;
            restoreTop = myField.scrollTop;

            myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);

            myField.selectionStart = startPos + myValue.length;
            myField.selectionEnd = startPos + myValue.length;

            if (restoreTop > 0) {
                myField.scrollTop = restoreTop;
            }
        }
        else {
            myField.value += myValue;
        }
    }

    function interceptTabs(evt, control) {
        key = evt.keyCode ? evt.keyCode : evt.which ? evt.which : evt.charCode;
        if (key == 9) {
            insertAtCursor(control, '\t');
            return false;
        }
        else {
            return key;
        }
    }

Open in new window

Avatar of dshrenik
dshrenik
Flag of United States of America image

ASKER

One approach could be to figure out the cursor position at the time of pressing the Return key, and count the number of TABs at the beginning of the line, and insert the same number after the line.
Is something like this implementable?
ASKER CERTIFIED SOLUTION
Avatar of dshrenik
dshrenik
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Terry Woods
Nice work... thanks for sharing!