Reputation: 921
I know there are smiliar questions but I didn't get my answer.
function setTextareaSelection(newText) {
var selText;
newText = "This is a text \n to insert";
var textarea = document.getElementById('textarea');
if (window.getSelection) {
var selText = "";
selText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
var selEnd = textarea.selectionEnd;
var selTextBefore = textarea.value.substring(0, textarea.selectionStart);
var selTextAfter = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
if (selText != "") {
textarea.value = selTextBefore + newText + selTextAfter;
textarea.setSelectionRange(selEnd, selEnd);
}
}
}
I want to place mouse cursor after the inserted text.
Firefox only
Online example: link text
Upvotes: 1
Views: 1188
Reputation: 195992
Actual code
function setTextareaSelection(newText) {
var selText;
newText="This is a text \n to insert" ;
var textarea=document.getElementById('textarea');
if (window.getSelection) {
var selText = "";
selText = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
var selEnd = textarea.selectionEnd;
var fromEnd = textarea.value.length - selEnd ;
var selTextBefore = textarea.value.substring(0, textarea.selectionStart);
var selTextAfter = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
if (selText != "") {
textarea.value = selTextBefore + newText + selTextAfter;
var curs = textarea.value.length - fromEnd
textarea.setSelectionRange(curs ,curs );
}
textarea.focus();
}
}
Upvotes: 0
Reputation: 324567
There's an issue with that code: why test for window.getSelection
when you never actually use it? It's the selectionStart
and selectionEnd
properties of the textarea you need to worry about. You should test for the feature you're about to use, not something completely unrelated based on what you know about a few browsers.
Here's a function that will do this in all major browsers, including IE (back to at least version 5, possibly 4). It's also shorter than what you've got now. I know you mentioned you only needed it to work in Firefox, but others may find the IE support useful.
function pasteIntoInput(el, 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();
}
}
pasteIntoInput(document.getElementById("yourTextareaId"), "NEW TEXT");
Upvotes: 1
Reputation: 30135
textarea.setSelectionRange(selTextBefore+newText.length, selTextBefore+newText.length);
Upvotes: 1