How to wrap selected text in a textarea?
Asked Answered
S

2

17

How can I get the user selected text (just inside textarea) and apply actions to it something like wrap the selection [#bold]selected text[/bold]?

Seller answered 11/11, 2009 at 1:24 Comment(0)
A
26

Building off what Soufiane posted, here's the code translated to jquery with the ability to pass in the open and close tags:

function wrapText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}

Usage would then be like so:

wrapText("myTextArea", "[#bold]", "[/bold]");
Aretha answered 11/11, 2009 at 2:18 Comment(4)
In case anyone ever wants it, here's a coffeescript version of this function: gist.github.com/2938205Trudge
Would be nice if the final selected text included the insertion, not only the initial selection. Or maybe jump the caret to the end of the new string...Larianna
Ok, this does the trick textArea[0].selectionEnd = end + openTag.length + closeTag.length; (after the last line).Larianna
To prevent the wrapper from being added at the beginning of the textarea when no text is selected, wrap the last line from @Aretha like so: if(selectedText != 0) { textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len)); }Neper
T
9
function wrapAsLink(url){
  var textarea = document.getElementById("myTa");
  var len = textarea.value.length;
  var start = textarea.selectionStart;
  var end = textarea.selectionEnd;
  var sel = textarea.value.substring(start, end);
  var replace = '<a href="'+url+'">' + sel + '</a>';
  textarea.value = textarea.value.substring(0,start) + replace +
  textarea.value.substring(end,len);
}

This function may help you to do what you want with some tweaks. I found it here.

Tremolite answered 11/11, 2009 at 1:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.