1

New to JavaScript and I'm trying to have a button copy some text in the code to the clipboard. This doesn't seem to work.. Please let me know what I'm missing. Thanks!

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Copy text</button>

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

</body>
</html>
Aaron Mazie
  • 763
  • 6
  • 15

1 Answers1

2

The reason it wasnt working is because you cant do to a varaible .select() so when you do a document.execCommand("copy") your copying any other selected text try putting the stuff in a input box and then try .select()

<!DOCTYPE html>
<html>
<body>
<input id="myId" value="myText"> </input>
<button onclick="myFunction()">Copy text</button>

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

</body>
</html>

and if you want to hide the textbox do

<!DOCTYPE html>
<html>
<body>
<input id="myId" value="myText" style="display:none;"> </input>
<button onclick="myFunction()">Copy text</button>

<script>
function myFunction() {
  var copyText = document.getElementById("myId");
  copyText.style = "display:inline";
  copyText.select();
  copyText.style = "display:none";
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

</body>
</html>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Dodo
  • 228
  • 1
  • 9
  • The second one is what I was looking for. Thought I figured it out but it doesn't work unless the input box is showing... – Aaron Mazie Jul 27 '18 at 23:28
  • 1
    can you press the check mark so it looks like the question is solved please? if you do stackoverflow gives 10 good boy points. – Dodo Jul 27 '18 at 23:37