mardi 18 septembre 2018

How to copy text from to clipboard

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



Aucun commentaire:

Enregistrer un commentaire