Set cursor to specific position on specific line in a textarea

Wesley Smith picture Wesley Smith · Jul 25, 2013 · Viewed 20k times · Source

I am trying to somewhat duplicate the "autocorrect" functionality seen in programs like Microsoft Office's Outlook.

For starters, anytime a user types "a " (the letter a and a space) at the beginning of a line I want to change that text to "*Agent ["

I have written the below which works fine if you are typing along in the textarea from top to bottom. But if you type anywhere else in the textarea the text is changed then the cursor moves to the end of the textarea.

I want the cursor to always be placed at the end of the changed text.

I have the line number that was changed in the variable currentLineNumber and i know the cursor needs to be after the 8th character in that line but I am unsure of how to tell it to go there

Ideally id like to something like

function setCursor(row, position) {
 //.... code to set cursor 
}

What can I do to accomplish this? Im open to a javascript or jQuery solution (although I find jQuery a little difficult to read and understand)

If there's a better way to achieve what I need overall, I'm open to that too.

Here's a jsFiddle if you don't understand the issue

Answer

Leon picture Leon · Jul 25, 2013

I've updated your fiddle see: http://jsfiddle.net/eghpf/2/

I've added var currentPosition which is used in this method

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

Which comes from this jQuery Set Cursor Position in Text Area

What happens (is the reason why the cursor is always on the last position); is when you call $('#systemNotesbuilder').val(arrayOfLines.join("\n")); the entire value gets overwritten with a new value placing the cursor after that new value. The call to set the cursor is (and should) be after that call.