Link to home
Start Free TrialLog in
Avatar of bertino12
bertino12

asked on

How to make a substring in RichTextBox to bold

I have a richtextbox that contains the string "I want to buy a new computer as soon as possible." and want to have a button to click that makes "as soon as" Bold. How can I do this?
Avatar of rae_rae
rae_rae
Flag of United States of America image

/**
* Replace selected elments with the element wrapped in a <tag></tag>
* This function is supposed to be cross-platform
* This function copied from http://codingforums.com/showthread.php?t=134113
*
* @return void
*/
function formatText(el,tag) {
      var selectedText=document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);// IE:Moz
      var newText='<'+tag+'>'+selectedText+'</'+tag+'>';
      // Do IE compatible replacements
      if(document.selection){
            document.selection.createRange().text=newText;
      }
      // Do mozilla compatible replacements
      else{
            el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
      }
}


Then call this like so input type="button" onclick="formatText('element', '<b>')"
ASKER CERTIFIED SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
richtextbox1.select allows you select from some index to some length of text.
After selecting, just make the selection bold as shown by jaime.
Indeed I showed how to use the Select method too.
 
Looks like Jaime is the winner here :)