0

I tried to copy by pressing a button, copy the value of input hidden. In JavaScript the value is obtained in var without problems, but it does not copy the value. What am I doing wrong?

 <div class="dropdown-divider"></div>
  <a class="dropdown-item" onclick="mycopyphone()">Copiar Telefono</a>    
   <input type="hidden" id="Key" value="'. $row["telefono"] .'" />
     <script>
          function mycopyphone() {
           var hidden = document.getElementById("Key").value;
            copyText = hidden;
             copyText.select();
              copyText.setSelectionRange(0, 99999)
               document.execCommand("copy");
               alert("Copied the text: " + copyText.value);
                }
       </script>
halfer
  • 19,824
  • 17
  • 99
  • 186
diaconu liviu
  • 1,032
  • 2
  • 13
  • 30

1 Answers1

1

Two problems. Hidden inputs don't support text selection, and it's the input element that has the select() function, not its value. You could do this instead:

<div class="dropdown-divider"></div>
<a class="dropdown-item" onclick="mycopyphone()">Copiar Telefono</a>
<input type="text" style="display:none;" id="Key" value="'. $row["telefono"] .'" />
<script>
  function mycopyphone() {
    var hidden = document.getElementById("Key");
    hidden.style.display = 'block';
    hidden.select();
    hidden.setSelectionRange(0, 99999)
    document.execCommand("copy");
    alert("Copied the text: " + hidden.value);
    hidden.style.display = 'none';
  }
</script>
Geat
  • 1,169
  • 6
  • 17
  • 1
    You're right, I thought it was something hidden, but I didn't know that it can't be copied. thanks for explaining, and thanks for your help. – diaconu liviu May 29 '20 at 21:59
  • It does not copy, it only puts the message that it has copied but it does not copy – diaconu liviu May 29 '20 at 22:07
  • 1
    already answered here - https://stackoverflow.com/questions/31593297/using-execcommand-javascript-to-copy-hidden-text-to-clipboard – takrishna May 29 '20 at 22:16
  • @takrishna is right. I've amended the answer so it copies correctly, but the "already answered" link shows how to do it. – Geat May 29 '20 at 22:27