Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inserting text at cursorposition else at the end of text in textarea in IE

 
venkateswara rao ravinuthala
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<script>
function insertAtCursor(text) {
var field = document.getElementById("Expression");
if (document.selection) {
field.focus();
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;
}
}
</script>
<body>
<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('(');">
</body>

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic