Can someone please tell me the code where clicking on a link populates a textarea with a little paragraph.

Dani AI

Generated

Nice — and had the right idea: clicking a link can fill a textarea. For a cleaner, more maintainable pattern that handles multi-line paragraphs and multiple links without inline handlers, keep the text in the page (using a <template>) and attach one unobtrusive listener that responds to links with a data attribute.

Example (HTML + JS):

<textarea id="note" rows="6" cols="50"></textarea>

<a href="#" class="fill" data-tpl="para1">Insert greeting</a>
<a href="#" class="fill" data-tpl="para2">Insert signature</a>

<template id="para1">
Hello,
This is a small paragraph that spans lines.
Best regards,
</template>

<template id="para2">
-- 
Jane Developer
Company Name
</template>

<script>
document.addEventListener('DOMContentLoaded', function () {
  var area = document.querySelector('#note');
  document.addEventListener('click', function (e) {
    var t = e.target;
    if (t.matches && t.matches('.fill')) {
      e.preventDefault();
      var tpl = document.getElementById(t.getAttribute('data-tpl'));
      if (tpl) area.value = tpl.textContent.replace(/\r/g, '');
      area.focus();
    }
  });
});
</script>

Why this helps: no inline onclick attributes, easy to add more links, and templates preserve line breaks and avoid escaping quotes. For browser details and DOM APIs used: see the MDN docs for EventTarget.addEventListener, HTML <template> element, and Element.matches.

Troubleshooting notes: make sure the script runs after DOM is ready (DOMContentLoaded), preventDefault to stop anchor navigation, and trim or replace carriage returns if pasted content includes CRLF. If older IE support is required, use progressively simpler fallbacks (hidden inputs or server-side insertion) since <template> and matches may not be available.

Recommended Answers

All 3 Replies

Unless I'm mistaken (and could be, since I haven't javascripted in a while), doesn't it matter which browser you are doing it for? (like, aren't the DOM's different for IE and mozilla?)

I think the w3c compliant version is:

document.getElementById('textboxnamehere').value="text to display";

Comatose is correct. Here is more detail.

<script type="text/javascript">
function ElementContent(id,content)
{
    document.getElementById(id).value = content;
}
</script>

<textarea id="ta1">&nbsp;</textarea>
<button value="Click Me!" onclick="ElementContent('ta1','Hey, it works.')" />

It worked! Thank you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.