Select and Copy input text onclick?

Viewed 26150

I've actually seen a few questions about this, most of them are from at least 5 or 6 years ago.

I want to have an input box:

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

Here's the JavaScript I've been trying to work with:

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

I know my code doesn't work. If I remove execCommand('copy'); then the alert() pops up, but it seems to be hitting an error at that line. I've tried making it this.execCommand('copy'); as well, not really sure what to do here.

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

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

Any ideas?

2 Answers

Use this function with your copy_btn (without onclick function).

function function_name() {
    var c = document.getElementById("copy");
    c.select();
    document.execCommand('copy');
}
Related