I want to include a button on an existing webpage that will copy text to the Windows clipboard.
The webpage and the PHP in it already works well to create and display text like this:
Output on webpage:
'Abby Normal' <abnormal@rockyhorror.com>, 'Brad Majors' <bm@rockyhorror.com>, 'Frank N. Furter' <franknfurter@rockyhorror.com>
So now I want to add a Javascript function and an html button that calls that function to copy that output to the Windows clipboard.
Problem: nothing is copied when the button is pressed. What am I doing wrong? Thank you in advance.
<?PHP
session_start();
include('include/_initsess.php');
include('include/_setdb.php');
if(!isset($_SESSION['userlist'])) exit;
$users = $_SESSION['userlist'];
$emails = '';
$qry = "SELECT FIRST,LAST,EMAIL FROM users WHERE PKEY IN ($users)";
$result = mysql_query($qry);
$numrows = mysql_num_rows($result);
for ($m=0; $m<$numrows; $m++) {
$row = mysql_fetch_array($result);
list($fn,$ln,$em) = $row;
$emails .= ($m==0) ? "'".$fn." ".$ln."' <".$em.">" : (", '".$fn." ".$ln."' <".$em.">");
} // end for
?>
<html>
<head>
</head>
<body>
<span class=mono id="theList" value="<?php echo $emails; ?>">
<?PHP echo($emails); ?>
</span>
<script>
function copyToClipboardWithJavascript() {
/* Get the text field */
var copyText = document.getElementById("theList");
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
}
</script>
<button onclick="copyToClipboardWithJavascript()">Click here</button>
</span>
</body>
</html>
I've tried the way a Javascript tutorial suggested:
var copyText = = document.getElementById("theList");
And my own variations using PHP within Javascript:
var copyText = <?PHP echo($emails); ?>;
var copyText = `<?PHP echo($emails); ?>`;
var copyText = "<?PHP echo($emails); ?>";
var copyText = '<?PHP echo($emails); ?>';
But the result is that nothing causes any errors and nothing is copied to the clipboard.
I know the web page is being immediately saved and used because I also make a trivial change to the letters 'Click here' in the button and can see the difference after refreshing.enter code here
***UPDATE WITH ANSWER I USED:****
<span class=mono id="theList">
<?PHP echo($emails); ?>
</span>
<button id="copyButton" onclick="myCopyFunction()">Copy email address list to clipboard.</button>
<script>
function myCopyFunction() {
var myText = document.createElement("textarea")
myText.value = document.getElementById("theList").innerHTML;
myText.value = myText.value.replace(/</g,"<");
myText.value = myText.value.replace(/>/g,">");
document.body.appendChild(myText)
myText.focus();
myText.select();
document.execCommand('copy');
document.body.removeChild(myText);
}
</script>