View Full Version : Insert into text area using javascript

07-26-2008, 11:25 AM
Hey, I was wanting to see if I could insert text into a text area using a javascript function

I want the text to be inserted where the cursor in the text area is at the time (much like the buttons at the top of this text area does, e.g. when you click the "code" button [[ CODE ]][[ /CODE ]] appears where the cursor is)

I just have no idea where to start and any help would be much appreciated, cheers

Philip M
07-26-2008, 11:35 AM
Is this what you re looking for?

<script type="text/javascript">

// myField accepts an object reference, myValue accepts the text string to insert at the cursor

function insertatcursor(myField, myValue) {
if (document.selection) {
sel = document.selection.createRange();
sel.text = myValue;
else if (myField.selectionStart == 0 || myField.selectionStart == '0') {
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;


<textarea id="mytext" rows="8" cols="70"></textarea> <br><br>
<button onclick="insertatcursor(document.getElementById('mytext'),'This is the inserted text')">Insert text at cursor</button>

Quizmaster: During World War Two, in June 1940, Paris was captured by troops from which country?
Contestant: England