开发者

insert text into textarea with jQuery

I have a textarea and a list of several variable outside of it. I need to be able to click on a variable and p开发者_StackOverflowlace it into the text area.

<div id="var1" class="insert">Name</div>
<div id="var2" class="insert">Street address</div>

<textarea id="targetText">some text already here</textarea>

After insert I need it to look like:

<textarea id="targetText">some text already here {Street address}</textarea>

I was thinking of using click function:

$(".insert").click(function () {
        // some magic to add to textarea
});


If you want to insert the variable at the cursor, you'll need to use selectionStart as follows:

$('.insert').click(function(e){
    var tav    = $('#targetText').val(),
        strPos = $('#targetText')[0].selectionStart;
        front  = (tav).substring(0,strPos),
        back   = (tav).substring(strPos,tav.length); 

    $('#targetText').val(front + '{' + $(this).text() + '}' + back);
});

See fiddle: http://jsfiddle.net/rKmVL/1/

Note: This probably won't work as-is in IE.


try this:

$(".insert").click(function () {
    var insertText = $(this).text();
       $('#targetText').append(" "+insertText);
});

demo: http://jsfiddle.net/Wkz6U/


$("#targetText").val($("#targetText").val() + "{" + $(this).text() + "}");

feel the magic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜