Professorval
Professorval

Reputation: 323

Copying PHP variables to the clipboard with javascript

I'm trying to copy values generated using a foreach loop to the clipboard using JS. Only the first row gets copied, no matter which row is clicked.

Here is the code producing the values to be copied:

foreach($results_array as $value) {
    /*Some PHP code*/ 
    <input class="col-sm-10" title="Copy Link" type="text" id="copy_this" value='<?php echo  $user_folder."/".$value; ?>' onclick="copyTo()"/>
}

My JS function:

function copyTo() {
  /* Get the text field */
  var copyText = document.getElementById("copy_this");
                                
  /* Copy the text inside the text field */
  document.execCommand("copy");
}

Upvotes: 1

Views: 1380

Answers (1)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146588

The whole purpose of IDs is to uniquely IDentify an element. Also, that's not how execCommand() works (how can your code possibly know that text you want copied?).

Getting rid of IDs (which you don't really need at all) you could do something like:

function copyTo(input) {
  input.select();
  document.execCommand("copy");
}
<input type="text" value="First" onclick="copyTo(this)">
<input type="text" value="Second" onclick="copyTo(this)">
<input type="text" value="Third" onclick="copyTo(this)">

Upvotes: 1

Related Questions