1

I have many textareas on my page

<textarea onClick="copyToClipboard(this);">mobile</textarea>
<textarea onClick="copyToClipboard(this);">computer</textarea>
<textarea onClick="copyToClipboard(this);">chair</textarea>
.
.
.

I want to select the text and copy to clipboard when focused that textarea in pure JavaScript without using any library.

My js code is

function copyToClipboard()
{
   this.select(); // I don't know how to select in JavaScript
   document.execCommand("copy");

}
Syed
  • 736
  • 1
  • 7
  • 24
  • 1
    Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Dhaval Marthak Jan 15 '19 at 06:13

2 Answers2

2

You will get the selected text using window.getSelection() function with pure Javascript.

I've edited the code as per your requirements. To get all the textarea content selected use select() function.

function copyToClipboard(elem) {
console.log(elem.value)
 elem.focus();
 elem.select();

document.getElementById('text').innerHTML = window.getSelection();
document.execCommand("copy");
}
<textarea class onClick="copyToClipboard(this)">Computer</textarea>
<textarea class onClick="copyToClipboard(this)">Mouse</textarea>
<textarea class onClick="copyToClipboard(this)">Keyboard</textarea>

<p id="text"></p>
1

Try it:

var el = document.querySelectorAll('textarea');

for (var i = 0; i < el.length; i++) {
  el[i].addEventListener('click', (e) => {
    e.target.select();
    document.execCommand("copy");
  });
}
<textarea>mobile</textarea>
<textarea>computer</textarea>
<textarea>chair</textarea>
meine
  • 191
  • 4
  • 12