views:

14892

answers:

10

Hey, 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.

Thankyou.

+6  A: 

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");
});
Jason
Thanks, i'll give it a go, I am new to jQuery so am not aware of all of the easy to use functions.
Oliver Stubley
i'm relatively new too. it's fun and super easy once you get the hang of it. Check this out for more reference: http://docs.jquery.com/Main_Page
Jason
Thankyou very much, glad to know I'm not the only one that doesn't fully know jQuery as most people seem to do!
Oliver Stubley
+13  A: 

I use this function in my code:

$.fn.extend({
    insertAtCaret: function(myValue){
      if (document.selection) {
        this.focus();
        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();
      }
    }
})

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

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

Thinker
Does this highlight inserted text also?
Oliver Stubley
Nope, but this work better than solution you accepted.
Thinker
The solution I accepted is simpler and works fine, thanks.
Oliver Stubley
But that solution won't work, when user move his cursor somewhere back :) Anyway, nevermind.
Thinker
you use 'this' as both a wrapped set and an element. hmmm .. just tried and it doesn't work w/o edits
Scott Evernden
hi, I tried this code and it simply doesn't work ... @Scott: how did you get tinker with this to get it working? Thanks :)
sillyMunky
This code requires jQuery.
Thinker
I couldn't get this code to work either. I'm using jQuery. I tried both a textarea and a text field. I believe this.value for instance should be this.val(), etc..
Nick
Yeah on IE it kept inserting at the top of the DOM and on Fox it did nothing. Using latest JQuery...
Caveatrob
Doesn't work for me neither.
rebellion
+6  A: 

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'); 
})
TStamper
Thankyou very much, TStamper!
Oliver Stubley
check my answer for a much easier way to append text
Jason
@Jason- sorry not true , append expects html data starting with a html element ex: <p
TStamper
+1  A: 

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

Russ Cam
+2  A: 

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.

panchicore
Not enough jQuery. :) If seriously, my down vote for non-english variable names.
temoto
A: 

I used that and it work fine :)

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

Remi

Remi
A: 

I want to do something similar: have text people can click on in page A and have it injected into textarea on page B.

I'm adapting some javascript and want to do this with jQuery:

function DoneLoading(){
  //setDefaults();

}

function setDefaults(){
      document.getElementById("quote").value = "<?php
if(isset($_REQUEST["quote"])){
echo $_REQUEST["quote"];
} else {
echo "Type Your Quote Here!";
}
?>";

Can you point me in the right direction for accomplishing this with jQuery?

valerie
+7  A: 

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

$.fn.extend({
insertAtCaret: function(myValue){
  this.each(function(i) {
    if (document.selection) {
      this.focus();
      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();
    }
  })
}

})

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

$('#element1, #element2, #element3, .class-of-elements').insertAtCaret('text');
Aniebiet Udoh
There is a trailing }) in the anwer so at first I tought that solution wasn't working, but after fixing it, it works great in IE7 and FF3.5. You can insert a piece of text at caret for a TEXTAREA element. Thank you!
Philippe
this also works in Chrome. thanks for saving me some time :) and thank you to @Thinker for the original code.
Veli
A: 

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

})

Bandpay
+1  A: 

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.

Marcus