Jerry
Jerry

Reputation: 71

jquery inserting text to textarea after X characters

    var currentposition = 10; // after 10 characters
    var text = ":)";

    $(".insert").click(function () {
           // Need help here
    });

<textarea id="messagebox">Example text for the code</textarea>

How can I insert text in a textarea after a certain amount of characters (there is text in the textarea), in this case 10. There also may not be any text in the textarea at all, in which case currentposition will be 0.

The purpose of this code is to enter smileys at the current cursor position.

Upvotes: 2

Views: 962

Answers (1)

DarkAjax
DarkAjax

Reputation: 16223

I'd recommend using something like .substring():

var currentposition = 10;
var text = ":)";

$('textarea').val($('textarea').val().substring(0,currentposition) + text + 
    $('textarea').val().substring (currentposition));

Jsfiddle example

UPDATE: If you want to have the cursor positioned at the end of the text, you can try calling the .focus() method before changing the textarea's value:

$('textarea').focus().val($('textarea').val().substring(0,position) + ' :) ' + 
    $('textarea').val().substring (position));

But I'm not sure it'll work in all browsers (there may be issues with IE)

Upvotes: 4

Related Questions