Profile photo
Submitted by G-Stone
on May 3rd, 2011 at 13:22:30 EST

How to insert text into TextArea at the cursor position using Javascript?

I am trying to insert text into TextArea box dynamically at the cursor position. I can append to the end but I am looking for some kind of Javascript to insert at cursor position.


Profile photo
Replied by SBajra
on May 3rd, 2011 at 13:30:57 EST
you need to get the caret position in the textArea control and insert your text.

Try this Javascript function:

<script type="text/javascript">
function InsertCodeInTextArea(textValue) {
//Get textArea HTML control
var txtArea = document.getElementById("txtTextArea");

if (document.selection) {
var sel = document.selection.createRange();
sel.text = textValue;
//Firefox, chrome, mozilla
else if (txtArea.selectionStart || txtArea.selectionStart == '0') {
var startPos = txtArea.selectionStart;
var endPos = txtArea.selectionEnd;
var scrollTop = txtArea.scrollTop;
txtArea.value = txtArea.value.substring(0, startPos) + textValue + txtArea.value.substring(endPos, txtArea.value.length);
txtArea.selectionStart = startPos + textValue.length;
txtArea.selectionEnd = startPos + textValue.length;
else {
txtArea.value += textArea.value;

There is specific logic for IE and most of the browsers. This Javascript function takes in text to be inserted into TextArea box. I hope this helps.
Accepted Answer

Profile photo
Replied by G-Stone
on May 11th, 2011 at 08:43:00 EST
Thanks Sbuch

Profile photo
Replied by Sandhya Singh
on June 22nd, 2012 at 01:57:18 EST
Hai friends i am new to javascript could any one help me in displaying textbox with in the textbox when key up is pressed using javascript...please.

Thanks in advance

Profile photo
Replied by SBajra
on June 22nd, 2012 at 06:28:45 EST
Hi Sandhya,
Can you please explain your question? Technically you can not display textbox within the textbox.

Profile photo
Replied by SBajra
on June 22nd, 2012 at 06:41:58 EST
However, you can add various events to textbox keyup event using Javascript