...

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



Hamza7
07-27-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:

DaveyErwin
07-27-2011, 08:40 PM
well something like this I guess ?



<script>
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() == ""){
document.getElementById('dsply').innerHTML="";
return
}
if (arg == 1){
document.getElementById('dsply').innerHTML="<h1>"+getSelText()+"</h1>";
return
}
if (arg == 2){
document.getElementById('dsply').innerHTML="<bold>"+getSelText()+"</bold>";
return
}
if (arg == 3){
document.getElementById('dsply').innerHTML="<i>"+getSelText()+"</i>";
return
}

}

</script>

<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.
</textarea>
<select onchange="doIt(selectedIndex);selectedIndex=0">
<option>pick a tag
<option>H1
<option>BOLD
<option>ITALISIZE
</select>
</form><div id=dsply></div>



document.getElementById('dsply').innerHTML="<bold>"+getSelText()+"</bold>";
There is no <bold> tag, just another typo,
of course there is a <b> tag.

Krupski
07-28-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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum