'Javascript CopytoClipboard function only copies 1 line

I have a PHP script which will print out a list of items. I wanted to add a button on there which copies the one or more items in the list to the clipboard. I have found a basic Javascript function that seems to work nicely.

However if I get more than 2 lines, the copy function will only copy the first line. How can I do this correctly?

if (isset($_POST['create'])){
    echo'<div class =" col-md-6 pull-right"><h3>Tokens you just generated below</h3><br>';
    if((isset($_POST['create']) && ($insert_token && $stmt->rowCount())) >0){
        foreach ($generatedtokens as $tokens){
            $ListTokens = ($tokens['token'].' - '.$tokens['desc'].'<br>');
            echo '<p id="tokens">'.nl2br($ListTokens).'</p>';
        }
        if (isset($_POST['create'])){
            ?>
            <button onclick="copyToClipboard('#tokens')" class ="btn btn-primary">Copy Tokens</button>
            <?php
            echo '</div>';
        }
    }
}
?>
<script>
    function copyToClipboard(element) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val($(element).text()).select();
        document.execCommand("copy");
        $temp.remove();
    }
</script>


Solution 1:[1]

I've edited the example you've posted using a textarea. Now the line breaks are also copied.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

    <div id="items">
        <p>Item 1</p>
        <p>Item 2</p>
        <p>Item 3</p>
        <p>Item 4</p>
    </div>

    <button onclick="copyToClipboard();" class ="btn btn-primary">Copy Tokens</button>
    <script>

    function copyToClipboard() 
    {
        var texts = [];
        var text = $('#items p')
        var txtarea = document.createElement('textarea');
        document.body.appendChild(txtarea);

        text.each(function(index, value)
        {
            txtarea.append(value.innerHTML + '\n');
        });

        txtarea.select();
        document.execCommand('copy');
        document.body.removeChild(txtarea);
    }

    </script>
</body>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1