Copy to clipboard using jquery?

html:

<button address="any text" class="btn btn-login copyToClipboard"><span> copy</span>

js file:

$('.copyToClipboard').click(function () {
        let str = $(this).attr('address');
        const el = document.createElement('textarea');
        el.value = str;
        el.setAttribute('readonly', '');
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
    })

You have an error on this line:

$temp.val($(value).text()).select();

Since value is already a string, you don't need to try to get it as an input field. Simply use this:

$temp.val(value).select();

Here's a working example.


var copyToClipboard = function (text) {
            var $txt = $('<textarea />');    
            $txt.val(text).css({ width: "1px", height: "1px" }).appendTo('body');
            $txt.select();    
            if (document.execCommand('copy')) {
                $txt.remove();
            }
        };

Tags:

Jquery