<input id="test" value="Test" disabled />
<a onclick="copy()">Button</a>
function copy(){
var text = document.getElementById("test");
text.select();
document.execCommand("copy");
console.log("Copied the text: " + text.value);
}
I have above function to copy my copy. But its not working.
There are a few issues with your code:
disable
attribute on the input has to actually be disabled
disabled
on the input, you cannot select its text in order to copy it, so you might either want to use readonly
in this case or set text.value
manually via navigator.clipboard.writeText(text.value)
function copy(){ var text = document.getElementById("test"); // set arbitrary value instead of current selection // to clipboard to make it work with a disabled input as well navigator.clipboard.writeText(text.value); // text.select(); //document.execCommand("copy"); console.log("Copied the text: " + text.value); } function copy2(){ var text = document.getElementById("test2"); text.select(); document.execCommand("copy"); console.log("Copied the text: " + text.value); }
<input id="test" value="Test" disabled /> <a onclick="copy()">Button</a> <hr> <h3>using <code>document.execCommand("copy")</code></h3> <input id="test2" value="Test2" readonly /> <a onclick="copy2()">Button</a>
You could use this clipboard.js library. It has a great browser support.
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.