How to save tab level in text box when pressing Enter?

When the user presses the enter button, I want the cursor to move to a new line, but if they are currently indented by two tabs, the cursor should remain indented in two tabs.

I have already implemented the ignore tab event to stop the focus from moving inside the page, so now I am looking for logic to keep the tab level on a new line.

if(e.keyCode === 13){

    //Logic here
}
+3
source share
1 answer

http://jsfiddle.net/DVKbn/

$("textarea").keydown(function(e){
    if(e.keyCode == 13){

        // assuming 'this' is textarea

        var cursorPos = this.selectionStart;
        var curentLine = this.value.substr(0, this.selectionStart).split("\n").pop();
        var indent = curentLine.match(/^\s*/)[0];
        var value = this.value;
        var textBefore = value.substring(0,  cursorPos );
        var textAfter  = value.substring( cursorPos, value.length );

        e.preventDefault(); // avoid creating a new line since we do it ourself
        this.value = textBefore + "\n" + indent + textAfter;
        setCaretPosition(this, cursorPos + indent.length + 1); // +1 is for the \n
    }
});

function setCaretPosition(ctrl, pos)
{

    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}
+4
source

All Articles