Set the cursor to a specific position on a specific line in the text box

I am trying to duplicate some of the "AutoCorrect" functionality seen in programs such as Microsoft Office Outlook.

To start, when the user enters "a" (letter a and a space) at the beginning of the line, I want to change this text to "* Agent ["

I wrote below, which works great if you type in the text box from top to bottom. But if you type somewhere else in the text box the text changes, the cursor moves to the end of the text box.

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

I have the line number that was changed in the currentLineNumber variable, and I know that the cursor should be after the eighth character in this line, but I'm not sure how to tell it to go there

Ideally, id looks like something like

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

What can I do for this? I am open to javascript or jQuery solution (although I find jQuery a bit difficult to read and understand)

If there is a better way to achieve what I need as a whole, I am also open to this.

Here's jsFiddle if you don't understand the problem

+7
javascript jquery textselection cursor textarea
source share
1 answer

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

I 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 of this jQuery Set cursor position in text area

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

+10
source share

All Articles