Search code examples
javascriptphpvariablescopy

onclick= copyToClipboard: for php variable using JavaScript


So I use the following code in php to copy any div, but how can I edit the js code to copy a php variable in the page, like $bookid or $row[1] (or copy/echo two strings like $bookid . $row[1] with one click) etc.?

<button onclick="copyToClipboard('#div1')\">Copy</button>

js code:

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

Solution

  • The text that gets copied here, is the content of the dynamically created input field. Currently that gets set by reading the text content of element - so that is the part that needs replacing.

    function copyToClipboard(textToCopy) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val(textToCopy).select();
      document.execCommand("copy");
      $temp.remove();
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button onclick="copyToClipboard('hello world')">Copy</button>