Monday, May 20, 2024
56
rated 0 times [  58] [ 2]  / answers: 1 / hits: 19398  / 15 Years ago, wed, april 15, 2009, 12:00:00

The script below will replace selected word in a textarea. But it only works on IE. Any idea how to make it work on Firefox? (The problem seems to lie in (document.all)? document.selection.createRange() : document.getSelection();)



<SCRIPT LANGUAGE=JavaScript>
<!--//
var seltext = null;
var repltext = null;
function replaceit()
{
seltext = (document.all)? document.selection.createRange() : document.getSelection();
var selit = (document.all)? document.selection.createRange().text : document.getSelection();
if (selit.length>=1){
if (seltext) {
repltext= prompt('Please enter the word to replace:', ' ');
if ((repltext==' ')||(repltext==null)) repltext=seltext.text;
seltext.text = repltext;
window.focus()
}
}
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<form name=f>
<textarea cols='40' rows='10' name='msg'></textarea>

<input type=button name=b value=Replace onClick=replaceit();>
</form>
</BODY>

More From » cross-browser

 Answers
14

OK, so document.getSelection() returns a string in FF. String::text does not exist. So you can't set that.



The basc idea of what you need to do (and it'll work in both browsers):



Get the text area by its id--you'll need to set an id attribute on the textarea. Get the starting and ending positions of the selection. Then take three substrings: 0->start, start->end, end->string.length. Replace the middle substring with whatever they put in the prompt. Set the text of the textarea to your newly formed string.



The exact how is up to you, I just gave you a flavor of the procedure.


[#99702] Wednesday, April 8, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yaquelina

Total Points: 517
Total Questions: 101
Total Answers: 96

Location: Egypt
Member since Tue, Jul 6, 2021
3 Years ago
yaquelina questions
;