View Full Version : How to wrap a selected text in a TextArea?

Jul 27th, 2011, 07:46 PM
I searched about this problem over Internet and found the same result many times, I found this example on stackoverflow (http://stackoverflow.com/questions/1712417/jquery-wrap-selected-text-in-a-textarea) but this example didn't work in my project; I am making a toolbar with buttons that insert HTML tags around the selected text in a <textarea>, this exemple didn't work because when the user click on a button the selected text won't be selected anymore because <textarea> loses focus and selected text will be unselected, I am targeting Firefox and compatible browsers so you don't need to give me the IE code; jQuery codes are accepted; so, have you any idea? :confused:

Jul 27th, 2011, 08:40 PM
well something like this I guess ?

function getSelText()
var txt = '';
if (window.getSelection)
return window.getSelection();
else if (document.getSelection)
return document.getSelection();
else if (document.selection)
return document.selection.createRange().text;
else return;
document.aform.selectedtext.value = txt;

function doIt(arg){
if (!arg || getSelText() == ""){
if (arg == 1){
if (arg == 2){
if (arg == 3){



<form name=aform >
<textarea name="selectedtext" rows="5" cols="20">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin luctus tristique nunc suscipit dapibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi a risus non diam porta pulvinar vitae eu massa. Aliquam et odio vel massa aliquet cursus. Pellentesque sed vehicula dolor. Sed vel metus mi. Phasellus sed hendrerit erat. Vivamus fringilla posuere ante ac laoreet. Vivamus hendrerit tristique cursus. Ut at vehicula felis. Nunc mollis orci id tortor porttitor ultrices. Etiam quis consectetur ipsum. Mauris pharetra ullamcorper augue, non mollis sapien gravida ut.
<select onchange="doIt(selectedIndex);selectedIndex=0">
<option>pick a tag
</form><div id=dsply></div>

There is no <bold> tag, just another typo,
of course there is a <b> tag.

Jul 28th, 2011, 05:21 PM
How to wrap a selected text in a TextArea?

Check this out: http://www.massless.org/mozedit

Should be all you need plus a little more.

Do a "view source" to grab all the code.