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>
2

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

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...
can you press the check mark so it looks like the question is solved please? if you do stackoverflow gives 10 good boy points.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.