1

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.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
user1506292
  • 13
  • 1
  • 4

1 Answers1

3

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();
    }
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thank you very much for your reply i can able to resolve my issue now. – user1506292 Jul 06 '12 at 13:39
  • Hi This is working fine if i am appending value of a button when i click it. I would also need in a requirement such that dropdown selected option should also get appended when i click a button. Its getting appended at 0 position instead of last. function addSyntax(){ var field = document.getElementById("operatorSelect"); var value = ''; if( field != '') { value = field.options[field.selectedIndex].value; insertAtCursorOld(value) field.selectedIndex = 0; } } Please help me with this. – user1506292 Jul 10 '12 at 09:49
  • @user1506292: That seems like a separate issue, although I don't fully understand what you're asking. Could you create an example? – Tim Down Jul 10 '12 at 10:09
  • In the example provided by you when i click the button when the cursor is in the middle of textarea text the provided text appending at the cursor position and immediatly the cursor is going back to end when i click second time continuously. I want it to be available there itself. This unselectable="on" thing is helping only half way. when i click at the border of the button then the cursor stays back else disappearing. Please help me with this. – user1506292 Jul 11 '12 at 09:40