6

I have a TextArea, textBox and a button. TextArea has some text e.g This is a cat.

Now my requirement is If someone set cursor position in TextArea and enter text in textbox and click on button the text should be append in cursor position instead of last. e.g.

TextArea: This is a cat. Cursor position: after "a" Entered Text in TextBox: black

Output: This is a black cat.

How can I do this using javascript.

Thanks in advance.

  • possible duplicate of [Inserting a text where cursor is using Javascript/jquery](http://stackoverflow.com/questions/1064089/inserting-a-text-where-cursor-is-using-javascript-jquery) – user Jul 26 '15 at 05:47
  • Possible duplicate of [Inserting text at cursor in a textarea, with Javascript](http://stackoverflow.com/questions/3308292/inserting-text-at-cursor-in-a-textarea-with-javascript) – Jason C Mar 29 '17 at 23:00

2 Answers2

5

I've answered this before:

Inserting text at cursor in a textarea, with Javascript

One extra note is that IE will lose the caret position by the time a click event fires on a button. To get round this you can either use themousedown event instead, or make the button unselectable by adding an unselectable="on" attribute.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

Using Google: How do I add text to a textarea at the cursor location using javascript

Copy the code from the above post (The one by Tim Down) and replace

insertTextAtCaret(textarea, "[INSERTED]");

with

var textBox = document.getElementById("your-textbox-name");
insertTextAtCaret(textarea, textbox.value);
Community
  • 1
  • 1
joostdevries
  • 930
  • 1
  • 6
  • 13