As you can see from the snippet, the "Copy to Clipboard" function works when the text comes from <input value="text">
, but I am failing to replicate the same function when the text comes from <a data-text="text">
.
I'm assuming copyText.select()
is limited to value from input
and textarea
only.
What would be the easiest way to make copy text from <a>
work?
function copyFromButton(id) {
alert("Clicked but not copied:" + document.getElementById(id).dataset.text);
/* Get the text field */
var copyText = document.getElementById(id).dataset.text;
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
function copyFromInput(id) {
/* Get the text field */
var copyText = document.getElementById(id);
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
<a class="btn" id="buttonCopy" data-text="text to be copied from button" onClick="copyFromButton(this.id)"> Cick to Copy </a>
<hr>
<input type="text" onclick="copyFromInput(this.id)" id="myInputRec" value="text to be copied from input" readonly="readonly" >