We help IT Professionals succeed at work.

Insert text into the cursor position of a textarea field using Javascript

Batalf
Batalf asked
on
Hi

I need some code for inserting some text at cursor-position of a textarea field, using Javascript.

Example:
I have a textarea field with some text. I place the cursor at one place in the middle of it, and then clicks a button. The button should then add some text at cursor-position of the Textarea-field.






Comment
Watch Question

Commented:
Can't be done! The browser has no way of knowing where the cursor is (without resorting to ActiveX).
Commented:
here's some html editing code that works with ie.  it won't work on netscape and doesn't work on mac...but if you have a limited environment.

<script language=javascript>
<!--

function markSelection ( txtObj ) {
  if ( txtObj.createTextRange ) {
    txtObj.caretPos = document.selection.createRange().duplicate();
    isSelected = true;
  }
}

function insertTag ( txtName, tag, enclose ) {
  var closeTag = tag;
  if ( enclose ) {
    var attribSplit = tag.indexOf ( ' ' );
    if ( tag.indexOf ( ' ' ) > -1 )
      closeTag = tag.substring ( 0, attribSplit );
  }
  if ( isSelected ) {
    var txtObj = eval ( "document.forms[0]." + txtName );
    if (txtObj.createTextRange && txtObj.caretPos) {
      var caretPos = txtObj.caretPos;
      caretPos.text = ( ( enclose ) ? "<"+tag+">"+caretPos.text+"</"+closeTag+">" : "<"+tag+">"+caretPos.text );
      markSelection ( txtObj );
      if ( txtObj.caretPos.text=='' ) {
        isSelected=false;
     txtObj.focus();
      }
    }
  } else {
    // placeholder for loss of focus handler
  }
}

//-->
</script>

<form>
<textarea name="tsttxt" ONSELECT="markSelection(this);" ONCLICK="markSelection(this);" ONKEYUP="markSelection(this);"><input type="button" value="BOLD" onClick="insertTag ( 'tsttxt', 'b', true )"> <input type="button" value="PARAGRAPH" onClick="insertTag ( 'tsttxt', 'p', false )">
</form>

Commented:
oops...forgot to close the textarea...oh well.
Top Expert 2005

Author

Commented:
To Droby10

Thanks a lot. After some adjustments, your code works just perfect.

Thanks a lot!

I know that these kinds of things won't work on Netscape or on Mac-platform, but my program is for IE users on Windows-platform, so it doesn't matter.

Batalf

Commented:
Brilliant!!! Thanks.

Ted Johnson

Explore More ContentExplore courses, solutions, and other research materials related to this topic.