faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

28 of 47 people (60%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

Can I insert a tag around a highlighted piece of text in a textarea with a button?

Dec 26th, 2001 01:19
Duvoor Kirthi, Fredrik Sjökvist, yes u can but only in IE4+


This can be done only in IE 4+.NN 4 does not give the selected text from
a textarea.but the document.getSelection method works in NN 4.only
trouble is that it does not return the selected text from within a
textarea.

below is a code that will add the <b> tag to the selected text.

<HTML>
<HEAD>
<TITLE>
selection manipulation in a text field with IE4+
</TITLE>

<SCRIPT>

function getbrowser() {
var browser = navigator.appName
var version = navigator.appVersion
var version1 = version.substring(22,25)
var sisop = version.substring(26,37)
var versionn = version.substring(0,3)
var sisopn = version.substring(11,16)
if ( browser== "Microsoft Internet Explorer" )
{
   alert("You are using the "+browser+", version "+version1+", with
"+sisop+"!");
   return 1;//for IE
}
if ( browser=="Netscape" )
{
alert("You are using the "+browser+", version "+versionn+", with
"+sisopn+"!");
}
if ( browser!="Netscape" && browser!="Microsoft Internet Explorer")
{
alert("You are using the "+browser+", version "+version+", with
"+sisop+"!");
}
}



function replacetext(textInput) 
{ 
if(getBrowser()==1)
{
if (document.selection) 
{
   var selectedRange = document.selection.createRange();
   if (selectedRange.parentElement() == textInput) 
   {
      var strSelection = document.selection.createRange().text ;
      if (strSelection == "") 
      { 
       return false; 
      } 
      else 
      {
         document.selection.createRange().text = "<B>" + strSelection +
"</B>"
         return;
      }
   }
   else
   {
      alert("You must select a text from within description to make it
bold");
   }
}
else
{
alert("You must select a text to make it bold");
}
}
else
{
 alert("Sorry for once Microsoft is Better.You can only Do this in
IE4+");
}
} 


</SCRIPT>

</HEAD>
<BODY>
<FORM NAME="formName">
<INPUT TYPE="button" VALUE="show content"  ONCLICK="replaceText(this);">
<BR>
<TEXTAREA NAME="textAreaName" ROWS="5" COLS="30">
Test For Getting Selection from a Textarea
</TEXTAREA>
<BR>

</FORM>

</BODY>
</HTML>

Hope this is useful to you