homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

How to insert text into a textarea

10+ Year Member

Msg#: 4686 posted 10:31 am on Nov 16, 2005 (gmt 0)

I'm trying to make a realtivly simple version of a CMS and I'd like to be able to insert text into a specific position by pressing something.

Say I insert a long text into a textarea, and I'd like to insert the text ***object28*** at a specific position, which I move my cursor to. Then I'd like to press an image,link or something else to insert that text at the exact position my cursor is at.

Wow, this was hard to explain, but I hope it is possible to understand anyhow.

Thanks for any help...



10+ Year Member

Msg#: 4686 posted 2:42 pm on Nov 16, 2005 (gmt 0)


Here is a function that I found somewhere on the net which should do what you want--it works in IE and Mozilla/Firefox I have added some comments for clarity.

<script type="text/javascript">

//myField accepts an object reference, myValue accepts the text strint to add
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {

//in effect we are creating a text range with zero
//length at the cursor location and replacing it
//with myValue
sel = document.selection.createRange();
sel.text = myValue;

//Mozilla/Firefox/Netscape 7+ support
else if (myField.selectionStart myField.selectionStart == '0') {

//Here we get the start and end points of the
//selection. Then we create substrings up to the
//start of the selection and from the end point
//of the selection to the end of the field value.
//Then we concatenate the first substring, myValue,
//and the second substring to get the new value.
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValue+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;


<style type="text/css">



<!--and now the test html--//>
<textarea id="myText" rows="8" cols="70"></textarea>
<button onclick="insertAtCursor(document.getElementById('myText'),'Test Text')">Add Test Text</button>

Hope this helps,


Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved