Insert text into textarea with jQuery

JqueryFormattingTextarea

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

Solution 3 - Jquery

I use this function in my code:

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

input{width:100px}
label{display:block;margin:10px 0}

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

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

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

Solution 4 - Jquery

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.

Solution 5 - Jquery

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.

Solution 6 - Jquery

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

Solution 7 - Jquery

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

Solution 8 - Jquery

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

Solution 9 - Jquery

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

Solution 10 - Jquery

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;

Solution 11 - Jquery

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

Solution 12 - Jquery

I think this would be better

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

Solution 13 - Jquery

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

Solution 14 - Jquery

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')

Solution 15 - Jquery

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

Solution 16 - Jquery

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

Solution 17 - Jquery

I used that and it work fine :)

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

Remi

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser114752View Question on Stackoverflow
Solution 1 - JqueryAniebiet UdohView Answer on Stackoverflow
Solution 2 - JqueryTStamperView Answer on Stackoverflow
Solution 3 - JqueryThinkerView Answer on Stackoverflow
Solution 4 - JqueryMarcusView Answer on Stackoverflow
Solution 5 - JquerypanchicoreView Answer on Stackoverflow
Solution 6 - JqueryBabak BandpayView Answer on Stackoverflow
Solution 7 - JqueryJasonView Answer on Stackoverflow
Solution 8 - JqueryRuss CamView Answer on Stackoverflow
Solution 9 - JqueryAvram CosminView Answer on Stackoverflow
Solution 10 - JqueryLongView Answer on Stackoverflow
Solution 11 - JqueryTechieView Answer on Stackoverflow
Solution 12 - Jqueryuser1201452View Answer on Stackoverflow
Solution 13 - Jqueryd.popovView Answer on Stackoverflow
Solution 14 - JquerySidTechs1View Answer on Stackoverflow
Solution 15 - JqueryDevView Answer on Stackoverflow
Solution 16 - JqueryGeorge SEDRAView Answer on Stackoverflow
Solution 17 - JqueryRemiView Answer on Stackoverflow