[jquery] Insert text into textarea with jQuery

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.

This question is related to jquery formatting textarea

The answer is


I use this function in my code:

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

It's not 100% mine, I googled it somewhere and then tuned for mine app.

Usage: $('#element').insertAtCaret('text');


Simple solution would be : (Assumption: You want whatever you type inside the textbox to get appended to what is already there in the textarea)

In the onClick event of the < a > tag,write a user-defined function, which does this:

function textType(){

  var **str1**=$("#textId1").val();

  var **str2**=$("#textId2").val();

  $("#textId1").val(str1+str2);

}

(where the ids,textId1- for o/p textArea textId2-for i/p textbox')


I used that and it work fine :)

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

Remi


I know this is an old question but for people searching for this solution it's worth noting that you should not use append() to add content to a textarea. the append() method targets innerHTML not the value of the textarea. The content may appear in the textarea but it will not be added to the element's form value.

As noted above using:

$('#textarea').val($('#textarea').val()+'new content'); 

will work fine.


This is similar to the answer given by @panchicore with a minor bug fixed.

function insertText(element, value) 
{
   var element_dom = document.getElementsByName(element)[0];
   if (document.selection) 
   {
      element_dom.focus();
      sel = document.selection.createRange();
      sel.text = value;
      return;
    } 
   if (element_dom.selectionStart || element_dom.selectionStart == "0") 
   {
     var t_start = element_dom.selectionStart;
     var t_end = element_dom.selectionEnd;
     var val_start = element_dom.value.substring(value, t_start);
     var val_end = element_dom.value.substring(t_end, element_dom.value.length);
     element_dom.value = val_start + value + val_end;
   } 
   else
   {
      element_dom.value += value;
   }
}

Another solution is described also here in case some of the other scripts does not work in your case.


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()); 
})

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


have you tried:

$("#yourAnchor").click(function () {
    $("#yourTextarea").val("your text");
});

not sure about autohighlighting, though.

EDIT:

To append:

$("#yourAnchor").click(function () {
    $("#yourTextarea").append("your text to append");
});

$.fn.extend({
    insertAtCaret: function(myValue) {
        var elemSelected = window.getSelection();
        if(elemSelected) {
            var startPos = elemSelected.getRangeAt(0).startOffset;
            var endPos = elemSelected.getRangeAt(0).endOffset;
            this.val(this.val().substring(0, startPos)+myValue+this.val().substring(endPos,this.val().length));
        } else {
            this.val(this.val()+ myValue) ;
        }
    }
});

I like the jQuery function extension. However, the this refers to the jQuery object not the DOM object. So I've modified it a little to make it even better (can update in multiple textboxes / textareas at once).

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();
    }
  });
}
});

This works really well. You can insert into multiple places at once, like:

$('#element1, #element2, #element3, .class-of-elements').insertAtCaret('text');

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;

Here is a quick solution that works in jQuery 1.9+:

a) Get caret position:

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;
    };

b) Append text at caret position:

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);
        }
    };

c) Example

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

    //append some text
    appendAtCaret($this, caret, 'Some text');
  });
});

Hej this is a modified version which works OK in FF @least for me and inserts at the carets position

  $.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();
   }
 }
})

this one allow you "inject" a piece of text to textbox, inject means: appends the text where cursor is.

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;
 }
}

And you can use it like this:

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

Funny and have more sence when we have "Insert Tag into Text" functionality.

works in all browsers.


I think this would be better

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

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to textarea

Get user input from textarea Set textarea width to 100% in bootstrap modal Remove scrollbars from textarea Add a scrollbar to a <textarea> Remove all stylings (border, glow) from textarea How to clear text area with a button in html using javascript? Get value from text area What character represents a new line in a text area Count textarea characters More than 1 row in <Input type="textarea" />