Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jul 2004
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Replacing highlighted text in textarea with value from textfield.

    Can someone help me out with this please?

    I have a form with a textarea, and a textfield.

    I want the user to be able to highlight a substring of the text they have pasted into the textarea, and replace it with text they have entered into the textfield.

    I'm sorry, but I am a JavaScript newbie so I can't figure this one out. It's for a JSP app I am trying to make.

    Thanks!

    PS: I should add that the text needs to be replaced using position, and not regex because the text may appear in more than one place within the same textarea.

  • #2
    Senior Coder
    Join Date
    Feb 2004
    Posts
    1,206
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Something like this?
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    
    <html>
    <head>
    <title>Text replacement</title>
    
    <script>
     function replaceText() {
      if(document.selection) { //IE
       if(document.selection.createRange().text != '') //nothing's selected
        document.selection.createRange().text = document.getElementById('txtField').value;
      }
      else { //Not IE.. assume Mozilla?
       var txtArea = document.getElementById('txtArea');
       var startPos = txtArea.selectionStart;
       var endPos = txtArea.selectionEnd;
     
       strSelection = txtArea.value.substring(startPos, endPos);	 
       if(strSelection == '') //nothing's selected
        return;
    		
       var text = document.getElementById('txtField').value;
       txtArea.value = txtArea.value.substring(0, startPos) + text + txtArea.value.substring(endPos, txtArea.value.length);
      }
     }
    </script>
    
    </head>
    <body>
    
    
    <input type="text" id="txtField"/>
    <button onclick="replaceText()">replace</button>
    <br>
    <textarea rows="10" cols="50" id="txtArea"></textarea>
    
    </body>
    </html>
    This will work in IE and Mozilla at least... I'm not sure about other browsers.

    Hope that helps, if you have any issues just post back.
    Sadiq.

  • #3
    New to the CF scene
    Join Date
    Jul 2004
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You are the man! Thanks, that is exactly what I am looking for. Now to modify it for my purposes.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •