Reputation: 13
I want to insert text in textarea at cursor position if cursor is placed else text should be appended at the end of existing text in IE.
I have used this function which is working fine in mozilla but not in ie where its appending at the starting position of existing text.
function insertAtCursor(text) {
var field = document.frmMain.Expression;
if (document.selection) {
field.focus();
sel = document.selection.createRange();
sel.text = text;
}
}
I want to append text at the end of existing text in ie if cursor is not placed.
Upvotes: 1
Views: 2602
Reputation: 324567
Check whether the field already has focus and use a TextRange
generated from the selection if so. If not, create a TextRange
for the field and collapse it to the end.
You don't appear to have any code for inserting text at the cursor in other browsers, but maybe you left that bit out.
Live demo: http://jsbin.com/ixoyes/2
Code:
function insertAtCursor(text) {
var field = document.frmMain.Expression;
if (document.selection) {
var range = document.selection.createRange();
if (!range || range.parentElement() != field) {
field.focus();
range = field.createTextRange();
range.collapse(false);
}
range.text = text;
range.collapse(false);
range.select();
}
}
Upvotes: 3