1

I have the following on a html page:

<div class="group>
  <textarea id="data" cols="20" rows="20"/>
  <a href="#" data-template="Some text">Use template</a> 
</div>

When I click the A tag I would like to fill the textarea under the same with the text included in its data-template.

How can I do this using JQuery?

Thank You, Miguel

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

3 Answers3

2

Or just

$('.group a').click(function(){
    $('#data').val($(this).data('template'));
});

Fiddle

RienNeVaPlu͢s
  • 7,442
  • 6
  • 43
  • 77
  • 1
    Why not @Ani? Tried it in FF & Chrome – RienNeVaPlu͢s Dec 15 '13 at 23:30
  • Because you are using `.val()` on `textarea` – Ani Dec 15 '13 at 23:31
  • Should it be `.html()` instead? (I'm no frequent jq user, but please enlighten us) – RienNeVaPlu͢s Dec 15 '13 at 23:32
  • 1
    http://api.jquery.com/val/ looks like it works just fine, but it will strip carriage returns. I'm curious why Ani doesn't like it though. I was unfamiliar w/the `data()` method til now, so I liked it! – Marc Dec 15 '13 at 23:33
  • [Here](http://stackoverflow.com/questions/415602/set-value-of-textarea-in-jquery) is another interesting discussion on using `val` for a `textarea` – RienNeVaPlu͢s Dec 15 '13 at 23:40
  • I had a problem with this ... If the text includes a line break, e.g. "Some text\nMoreText" I will get exactly that text in the textarea and the line break is not applied. I tried to use .text and .html instead of .val but it did not work ... any idea how to make this work? – Miguel Moura Dec 16 '13 at 10:54
  • @MDMoura you've to use `.replace(/\\n/g, "\n")` like [so](http://jsfiddle.net/Y7Kf7/10/) – RienNeVaPlu͢s Dec 16 '13 at 14:49
0

Firstly, you'll need to give the anchor an identifier of some sort:

<div class="group">
    <textarea id="data" cols="20" rows="20"/>
    <a id="yourid" href="#" data-template="Some text">Use template</a> 
</div>

... then you can use jQuery's append method:

$('#yourid').click(function(e) {
    e.preventDefault(); // stop the default click action
    var template = $(this).attr('data-template'); // Some text
    $('#data').append(template); // add to the textarea
});

You'll probably need to play around with how it formats it, maybe add in some line breaks before or after the appended content if you want to keep it on separate lines, e.g.:

$('#data').append("\n" + template);
scrowler
  • 24,273
  • 9
  • 60
  • 92
0

JS

$('#mylink').click(function() { 
    var text = $(this).attr("data-template")
    $('#data').append(text); 

});

HTML: Add id to Anchor tag

<a id="mylink" href="#" data-template="Some text">Use template</a> 
Ani
  • 4,473
  • 4
  • 26
  • 31