View Full Version : Replacing highlighted text in textarea with value from textfield.

07-06-2004, 07:10 PM
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.


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.

07-06-2004, 10:29 PM
Something like this?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Text replacement</title>

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

var text = document.getElementById('txtField').value;
txtArea.value = txtArea.value.substring(0, startPos) + text + txtArea.value.substring(endPos, txtArea.value.length);


<input type="text" id="txtField"/>
<button onclick="replaceText()">replace</button>
<textarea rows="10" cols="50" id="txtArea"></textarea>


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.

07-06-2004, 11:22 PM
You are the man! Thanks, that is exactly what I am looking for. Now to modify it for my purposes. :D