Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jul 2005
    Thanked 0 Times in 0 Posts

    Insert into text area using javascript

    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

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    London, England
    Thanked 2,573 Times in 2,551 Posts
    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


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts