0

Not much to add. This button has worked before. it would copy the code within it. Now whenever it is pressed the value="#code" is displayed to the user but not copied?

<input type="text" class="buttontxt" value="#Code" id="code" disabled>
<button class="button copy" onclick="myFunction()">Copy Code</button>

<script>
function myFunction() {
  var copyText = document.getElementById("code");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the code: " + copyText.value);
}
</script>

No idea why this has suddenly happened. It's broken in all of the browsers & on mobile. Would appreciate if someone could make this work again because I'm clueless.

phphelpplease
  • 131
  • 10

2 Answers2

0

Some commands need a value to be completed.

document.execCommand(command, showUI, value)

You need to pass the value.

Alexis Mateo
  • 57
  • 1
  • 7
  • `Some commands need a value to be completed`…however, `copy` isn't one of them. You can prove this anecdotally: try running `document.execCommand('copy', false, 'test')`—nothing copies. `document.execCommand('copy')` only works on text that has been selected within the DOM—values cannot be passed directly to the clipboard via the JS `aValueArgument` parameter. – aaplmath Aug 14 '18 at 00:49
0

The issue seems to lie in the fact that your input element is disabled. See this Stack Overflow post for more explanation, but you should change the disabled attribute to readonly so that your select() call can actually select the text. Right now, since the text is never selected, there is nothing to copy when document.execCommand("copy") is called, but since the text is accessible to JS, it shows up in the alert dialog as expected—hence the behavioral discrepancy. Here's a working version of your code:

<input type="text" class="buttontxt" value="#Code" id="code" readonly>
<button class="button copy" onclick="myFunction()">Copy Code</button>

<script>
function myFunction() {
  var copyText = document.getElementById("code");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the code: " + copyText.value);
}
</script>
aaplmath
  • 1,717
  • 1
  • 14
  • 27
  • Fixed it, thank you. I've hidden the text (made it white) any ideas on how to disable the border for just this one text element? – phphelpplease Aug 14 '18 at 02:06
  • @phphelpplease To hide the border, use the CSS `#code { border: none; }`. If you're looking to hide the `input` altogether, though, you might be better off using one of the solutions mentioned [here](https://stackoverflow.com/questions/31593297/using-execcommand-javascript-to-copy-hidden-text-to-clipboard) or [here](https://stackoverflow.com/questions/45561771/copy-text-from-a-hidden-control-using-javascript). – aaplmath Aug 14 '18 at 03:07