function insertAtCursor(text) {
var field = document.getElementById("Expression");
if (document.selection) {
sel = document.selection.createRange();
sel.text = text;
else if (field.selectionStart || field.selectionStart == '0') {
var startPos = field.selectionStart;
var endPos = field.selectionEnd;
field.value = field.value.substring(0, startPos)
+ text
+ field.value.substring(endPos, field.value.length);
} else {
field.value += text;
<textarea id="Expression" rows="5" cols="50">Put the caret in here and press the button or click outside and then press the button.</textarea>
<input type=button value=" ( " onclick="insertAtCursor('(');">

I am using the above function for appending the text in textarea when i click a button. In IE it is getting appended at the cursor position when cursor is placed else appending at the start of existing text in textarea.

I want to append the text at the end of existing text if cursor is not present else it should continue appending at the cursor position.

Please any one help me in this.
Thanks in advance.