传递给函数的值不会被复制

I pass the value from the HTML to the function for each item, and each time the function should reveal the code, copy it, and open a URL in a new window. Currently it reveals and opens the new window but I am unable to copy the revealed code!

function show_code(num, url, bookcode) {
  document.getElementById('revealedcode-' + num).style.display = '';
  document.getElementById('hiddencode-' + num).style.display = 'none';
  document.getElementById('codebox').style.display = 'none';
  $("#codebox").text(bookcode);
  var copytext = $("#codebox").text(bookcode)
  copytext.select();
  document.execCommand("copy");
  alert("Copied the text: " + copytext.value);
  window.open(url);
}

html is

<div class="right-pad clickbtn">
<a id="hiddencode-<?php echo $i; ?>"  href="#" onclick="show_code(<?php echo $i; ?>,'<?php echo $link ;?>','<?php echo $bookcode; ?>');">Show Code </a>

<a id="revealedcode-<?php echo $i; ?>"  style="display:none;" href="<?php echo $link ;?>"><?php echo $bookcode; ?></a>
</div>

       <div id="codebox"></div>

I expect the bookcode to be copied along with revealing it and opening the url passed to the function, currently for the alert it shows the value of copytext.value as undefined instead of the value in bookcode

The copy to clipboard functionality only works when the command is executed directly from the user, which means that the document.execCommand('copy'); command has to be in a function directly tied to the event listener.