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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.