0

I have button which inserts [link=enter link here] into a textarea. I would like so that when the button is pressed and the text is inserted into the textarea, the text enter link here is already selected, so that the user can easily enter the link. (This is identical to how Stack Overflow does this with how links are added in questions).

An issue is that say there was already [link=enter link here] in the textarea, if there was another [link=enter link here] added, I would like the one just added to be selected not the first one. Also I have a function which inserts the text at the location of the caret like so $('textarea').insertAtCaret('[link=enter text here]'); which makes things more difficult as there may be the text [link=enter text here] after.

One way of doing this is possibly by counting the number of times [link=enter link here] is in the textarea before the location of the caret THEN insert [link=enter link here] and then select the enter link here which appears after the count.

I've found a jQuery plugin called rangyinputs that allows me to select text. Though I have no idea how to use this to solve my issue.

Thanks in advance.

Pav Sidhu
  • 6,724
  • 18
  • 55
  • 110

1 Answers1

0

You need to use the select method

http://jsfiddle.net/fvLhbokd/

HTML

<textarea id="textArea">Enter some text here</textarea>

JavaScript

var textField = document.getElementById("textArea");
textField.focus();
textField.select();
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
  • How would I know where the location of the caret is and how would I select `[link=enter link here]` before it? – Pav Sidhu Aug 12 '15 at 16:34