Select and copy onclick input text?

I actually saw a few questions about this, most of them at least 5 or 6 years ago.

I want to have an input field:

<input id="copy-text" type="text" value="Click this text!">

Here is the JavaScript I was trying to work with:

document.getElementById("copy-text").onclick = function() {
  this.select();
  execCommand('copy');
  alert('This is a test...');
}

I know my code is not working. If I delete execCommand('copy');, then a message appears alert(), but it seems to be an error on this line. I tried to make it this.execCommand('copy');, and not quite sure what to do here.

Fiddle: https://jsfiddle.net/6v24k4sk/

The idea is that I want the user to click on the input field, he will select all the text and copy it to the clipboard.

Any ideas?

+4
source share
1 answer

You must place the document. before execCommand.

document.getElementById("copy-text").onclick = function() {
    this.select();
    document.execCommand('copy');
    alert('This is a test...');
}

: https://jsfiddle.net/9q3c1k20/

:

, . , , execCommand .

+10

All Articles