Replacing text inside textarea without focus

Posted by asker on Stack Overflow See other posts from Stack Overflow or by asker
Published on 2010-12-19T19:47:26Z Indexed on 2010/12/23 10:53 UTC
Read the original article Hit count: 340

Filed under:
|

I want to replace selected text(or insert new text after cursor position if nothing is selected). The new text is entered from another textbox.
I want to be able to insert new text without clicking first (focusing) in the textarea.
meaning: first select text to replace inside textarea, then enter new text into the textbox and click the button.

<textarea id='text' cols="40" rows="20">
</textarea>

<div id="opt">
    <input id="input" type="text" size="35">
    <input type="button" onclick='pasteIntoInput(document.getElementById("input").value)' value="button"/>    
</div>


function pasteIntoInput(text) { 
  el=document.getElementById("text");
  el.focus();    
  if (typeof el.selectionStart == "number"&& typeof el.selectionEnd == "number") { 
    var val = el.value; 
    var selStart = el.selectionStart;
    el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);        
    el.selectionEnd = el.selectionStart = selStart + text.length;
  } 
  else if (typeof document.selection != "undefined") {
    var textRange = document.selection.createRange();        
    textRange.text = text;       
    textRange.collapse(false);        
    textRange.select();
  } 
}  

Online example: link text

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html