Replacing selected text in a textarea

Discussion in 'JavaScript' started by noodleandy, May 15, 2007.

  1. #1
    Hi,

    I need help replacing text in a textarea, specifically creating a link tag around a piece of text (Exactly like the "insert link" button on this page)

    I've had trouble finding a cross-browser solution, but so far I can select the text successfully but just can't figure out how to replace it:

    
    function insert_link(){
    
    		var linktext;
    		var txtarea = document.getElementById('newstext');
    		
    		linktext = (txtarea.value).substring(txtarea.selectionStart,txtarea.selectionEnd);  
    
    		if (linktext == '')
    		{
    			alert("Please select some text for your link");
    		}
    		else
    		{
    			var linkurl = window.prompt('Please enter the URL of the link', 'http://');
    			
    			var htmllink = "<a href='" + linkurl + "'>" + linktext + "</a>";
    			
                            //How do I insert the html back into the textarea?
    		}
    	}
    Code (markup):
    Thanks for your help
     
    noodleandy, May 15, 2007 IP
  2. Aztral

    Aztral Well-Known Member

    Messages:
    344
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    125
    #2
    Are you trying to replace, or append?
     
    Aztral, May 16, 2007 IP
  3. noodleandy

    noodleandy Peon

    Messages:
    30
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Just want to wrap html tags around some text:

    So replace this:

    Link Text

    with this:

    <a href='http://www.link.com'>Link Text</a>
     
    noodleandy, May 17, 2007 IP
  4. bosko

    bosko Peon

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    See this page www dot massless dot org/mozedit/
    There you can find cross browser textarea editor and answer to your question.
     
    bosko, May 17, 2007 IP
  5. noodleandy

    noodleandy Peon

    Messages:
    30
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    thanks bosko, that did it!
     
    noodleandy, May 17, 2007 IP