0

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" >
j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    Put the output of `buttonCopy.dataSet.text` into the input, and then select/copy the new value? – evolutionxbox Sep 18 '18 at 08:46
  • Why do you pass only the element's id to the listener ? Just put `this` as argument, and you won't need to use `getElementById` in the listener's body. – Seblor Sep 18 '18 at 08:49
  • 3
    Possible duplicate of [How to copy text from a div to clipboard](https://stackoverflow.com/questions/36639681/how-to-copy-text-from-a-div-to-clipboard) – Liam Sep 18 '18 at 08:50
  • @Seblor I used this function for another part of my site, which reuses the same function with multiple inputs fields. – Federico Li Sep 18 '18 at 09:37

0 Answers0