Insert text into textarea with jQuery

2019-01-01 02:52发布

I'm wondering how I can insert text into a text area using jquery, upon the click of an anchor tag.

I don't want to replace text already in textarea, I want to append new text to textarea.

17条回答
琉璃瓶的回忆
2楼-- · 2019-01-01 03:31

It works good for me in Chrome 20.0.11

var startPos = this[0].selectionStart;
var endPos = this[0].selectionEnd;
var scrollTop = this.scrollTop;
this[0].value = this[0].value.substring(0, startPos) + myVal + this[0].value.substring(endPos, this[0].value.length);
this.focus();
this.selectionStart = startPos + myVal.length;
this.selectionEnd = startPos + myVal.length;
this.scrollTop = scrollTop;
查看更多
几人难应
3楼-- · 2019-01-01 03:32

If you want to append content to the textarea without replacing them, You can try the below

$('textarea').append('Whatever need to be added');

According to your scenario it would be

$('a').click(function() 
{ 
  $('textarea').append($('#area').val()); 
})
查看更多
路过你的时光
4楼-- · 2019-01-01 03:34

What you ask for should be reasonably straightforward in jQuery-

$(function() {
    $('#myAnchorId').click(function() { 
        var areaValue = $('#area').val();
        $('#area').val(areaValue + 'Whatever you want to enter');
    });
});

The best way that I can think of highlighting inserted text is by wrapping it in a span with a CSS class with background-color set to the color of your choice. On the next insert, you could remove the class from any existing spans (or strip the spans out).

However, There are plenty of free WYSIWYG HTML/Rich Text editors available on the market, I'm sure one will fit your needs

查看更多
一个人的天荒地老
5楼-- · 2019-01-01 03:34

I used that and it work fine :)

$("#textarea").html("Put here your content");

Remi

查看更多
春风洒进眼中
6楼-- · 2019-01-01 03:35

From what you have in Jason's comments try:

$('a').click(function() //this will apply to all anchor tags
{ 
   $('#area').val('foobar'); //this puts the textarea for the id labeled 'area'
})

Edit- To append to text look at below

$('a').click(function() //this will apply to all anchor tags
{ 
   $('#area').val($('#area').val()+'foobar'); 
})
查看更多
登录 后发表回答