Alex
Alex

Reputation: 68440

jQuery - inserting a string inside a textarea, then selecting a portion of it

Like SO has for example the B button:

**strong text**

But strong text to be automatically selected, and the cursor to be positioned just before the s

Upvotes: 2

Views: 408

Answers (1)

Tim Down
Tim Down

Reputation: 324557

You could use my Rangy Inputs jQuery plug-in now that I've finally got round to documenting it. Using it, the following will do the job:

$textArea = $("#yourtextarea");
$textArea.focus();
$textArea.surroundSelectedText("**", "**");

This will select the same text as was selected before, which is what SO does. However, if you prefer to have a caret before the "s" as you say then you can add the following:

$textArea.collapseSelection(true);

jsFiddle example: http://jsfiddle.net/AL7uY/

Upvotes: 2

Related Questions