使用jQuery将文本插入textarea

Oli*_*ley 150 formatting jquery textarea

我想知道如何在点击锚标签时使用jquery将文本插入文本区域.

我不想替换textarea中的文本,我想将新文本追加到textarea.

小智 186

我喜欢jQuery函数扩展.但是,指的是jQuery对象而不是DOM对象.所以我稍微修改了它以使其更好(可以同时在多个文本框/ textareas中更新).

jQuery.fn.extend({
insertAtCaret: function(myValue){
  return this.each(function(i) {
    if (document.selection) {
      //For browsers like Internet Explorer
      this.focus();
      var sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      //For browsers like Firefox and Webkit based
      var startPos = this.selectionStart;
      var endPos = this.selectionEnd;
      var scrollTop = this.scrollTop;
      this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
      this.focus();
      this.selectionStart = startPos + myValue.length;
      this.selectionEnd = startPos + myValue.length;
      this.scrollTop = scrollTop;
    } else {
      this.value += myValue;
      this.focus();
    }
  });
}
});
Run Code Online (Sandbox Code Playgroud)

这非常有效.您可以一次插入多个地方,例如:

$('#element1, #element2, #element3, .class-of-elements').insertAtCaret('text');
Run Code Online (Sandbox Code Playgroud)

  • "sel"是全球性的吗? (6认同)
  • 在anwer中有一个尾随})所以起初我认为解决方案不起作用,但在修复之后,它在IE7和FF3.5中运行良好.您可以在插入符号处插入一段TEXTAREA元素.谢谢! (3认同)

TSt*_*per 123

根据你在杰森的评论中所做的尝试:

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

编辑 -要附加到文本,请查看以下内容

$('a').click(function() //this will apply to all anchor tags
{ 
   $('#area').val($('#area').val()+'foobar'); 
})
Run Code Online (Sandbox Code Playgroud)

  • @Jason-抱歉不是真的,追加预期html数据以html元素开头:<p (8认同)

Thi*_*ker 46

我在我的代码中使用此函数:

$.fn.extend({
  insertAtCaret: function(myValue) {
    this.each(function() {
      if (document.selection) {
        this.focus();
        var sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
      } else if (this.selectionStart || this.selectionStart == '0') {
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.value = this.value.substring(0, startPos) +
          myValue + this.value.substring(endPos,this.value.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;
      } else {
        this.value += myValue;
        this.focus();
      }
    });
    return this;
  }
});
Run Code Online (Sandbox Code Playgroud)
input{width:100px}
label{display:block;margin:10px 0}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Copy text from: <input id="in2copy" type="text" value="x"></label>
<label>Insert text in: <input id="in2ins" type="text" value="1,2,3" autofocus></label>
<button onclick="$('#in2ins').insertAtCaret($('#in2copy').val())">Insert</button>
Run Code Online (Sandbox Code Playgroud)

这不是我的100%,我在某处搜索了一下然后调整了我的应用程序.

用法: $('#element').insertAtCaret('text');

  • 我也无法使用此代码.我正在使用jQuery.我尝试了textarea和文本字段.我相信this.value例如应该是this.val()等. (4认同)
  • 你使用'this'作为包装集和元素.嗯...只是尝试过,它无法正常编辑 (3认同)
  • 不,但这比你接受的解决方案更好. (2认同)
  • 但是当用户将光标移回某处时,该解决方案将无法工作:)无论如何,没关系. (2认同)

Mar*_*cus 19

我知道这是一个古老的问题,但对于寻找此解决方案的人来说,值得注意的是,您不应该使用append()将内容添加到textarea.append()方法的目标是innerHTML,而不是textarea的值.内容可能出现在textarea中,但不会添加到元素的表单值中.

如上所述使用:

$('#textarea').val($('#textarea').val()+'new content'); 
Run Code Online (Sandbox Code Playgroud)

会很好的.


pan*_*ore 13

这个允许你"注入"一段文本到文本框,注入意味着:将文本附加到光标所在的位置.

function inyectarTexto(elemento,valor){
 var elemento_dom=document.getElementsByName(elemento)[0];
 if(document.selection){
  elemento_dom.focus();
  sel=document.selection.createRange();
  sel.text=valor;
  return;
 }if(elemento_dom.selectionStart||elemento_dom.selectionStart=="0"){
  var t_start=elemento_dom.selectionStart;
  var t_end=elemento_dom.selectionEnd;
  var val_start=elemento_dom.value.substring(0,t_start);
  var val_end=elemento_dom.value.substring(t_end,elemento_dom.value.length);
  elemento_dom.value=val_start+valor+val_end;
 }else{
  elemento_dom.value+=valor;
 }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

<a href="javascript:void(0);" onclick="inyectarTexto('nametField','hello world');" >Say hello world to text</a>
Run Code Online (Sandbox Code Playgroud)

当我们有"将标签插入文本"功能时,有趣且有更多意义.

适用于所有浏览器.

  • @temoto:对非英语变量名称进行投票?它仍然完全可读.如果答案没有帮助,则应该使用向下投票按钮,这不是这里的情况.顺便说一下,当你投票时,它也会让你失去一些声望. (5认同)

Bab*_*pay 12

Hej这是一个修改过的版本,在FF @least中可以正常使用,并插入到插入位置

  $.fn.extend({
  insertAtCaret: function(myValue){
  var obj;
  if( typeof this[0].name !='undefined' ) obj = this[0];
  else obj = this;

  if ($.browser.msie) {
    obj.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
    obj.focus();
    }
  else if ($.browser.mozilla || $.browser.webkit) {
    var startPos = obj.selectionStart;
    var endPos = obj.selectionEnd;
    var scrollTop = obj.scrollTop;
    obj.value = obj.value.substring(0, startPos)+myValue+obj.value.substring(endPos,obj.value.length);
    obj.focus();
    obj.selectionStart = startPos + myValue.length;
    obj.selectionEnd = startPos + myValue.length;
    obj.scrollTop = scrollTop;
  } else {
    obj.value += myValue;
    obj.focus();
   }
 }
})
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 10

你有没有尝试过:

$("#yourAnchor").click(function () {
    $("#yourTextarea").val("your text");
});
Run Code Online (Sandbox Code Playgroud)

但不确定自动照明.

编辑:

附加:

$("#yourAnchor").click(function () {
    $("#yourTextarea").append("your text to append");
});
Run Code Online (Sandbox Code Playgroud)

  • 正如Marcus在下面所指出的,`append()`对`textarea`的值不起作用.`append()`方法的目标是innerHTML,而不是textarea的值. (5认同)

Rus*_*Cam 6

您要求的内容应该在jQuery中相当简单 -

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

我可以想到突出显示插入文本的最佳方法是将其包装在一个带有CSS类的范围中,并background-color设置为您选择的颜色.在下一个插入中,您可以从任何现有跨度中移除该类(或者将跨距移开).

但是,市场上有很多免费的WYSIWYG HTML/Rich Text编辑器,我相信它会满足您的需求


Avr*_*min 5

这是一个适用于jQuery 1.9+的快速解决方案:

a)获得插入位置:

function getCaret(el) {
        if (el.prop("selectionStart")) {
            return el.prop("selectionStart");
        } else if (document.selection) {
            el.focus();

            var r = document.selection.createRange();
            if (r == null) {
                return 0;
            }

            var re = el.createTextRange(),
                    rc = re.duplicate();
            re.moveToBookmark(r.getBookmark());
            rc.setEndPoint('EndToStart', re);

            return rc.text.length;
        }
        return 0;
    };
Run Code Online (Sandbox Code Playgroud)

b)在插入位置附加文本:

function appendAtCaret($target, caret, $value) {
        var value = $target.val();
        if (caret != value.length) {
            var startPos = $target.prop("selectionStart");
            var scrollTop = $target.scrollTop;
            $target.val(value.substring(0, caret) + ' ' + $value + ' ' + value.substring(caret, value.length));
            $target.prop("selectionStart", startPos + $value.length);
            $target.prop("selectionEnd", startPos + $value.length);
            $target.scrollTop = scrollTop;
        } else if (caret == 0)
        {
            $target.val($value + ' ' + value);
        } else {
            $target.val(value + ' ' + $value);
        }
    };
Run Code Online (Sandbox Code Playgroud)

c)例子

$('textarea').each(function() {
  var $this = $(this);
  $this.click(function() {
    //get caret position
    var caret = getCaret($this);

    //append some text
    appendAtCaret($this, caret, 'Some text');
  });
});
Run Code Online (Sandbox Code Playgroud)