DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

Copy To Clipboard JQuery Example

In this tutorial I will explain you how to copy to clipboard jquery example, many time we have requirement to copy text value one field to another field, like current address and perminant address etc. If you are working with inputs or textarea or div, you might need to create a button like "Copy to Clipboard" to copy all contents of input or div to user's clipboard using jquery or javascript.

So, here I will give you some piece of code how to copy to clipboard using JQuery.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Copy to clipboard using jquery example - techsolutionstuff.cpm</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            alert("Success");
            $("textarea").select();
            document.execCommand('copy');
        });

    });
</script>
</head>
<body>
  <h3>Copy To Clipboard JQuery Example - techsolutionstuff.com</h3>
    <textarea id="comment" rows="5" cols="62"></textarea>
    <p><button type="button">Copy To Clipboard</button></p>
    <p><strong>Note:</strong> Type something in the textarea and click the button to see the output.</p>
</body>
</html> 
Enter fullscreen mode Exit fullscreen mode

Read More : How To Check Array Is Empty Or Null In Javascript


You will get output like this :

copy to clipboard jquery example


You might also like :

Discussion (1)

Collapse
lukeshiru profile image
LUKESHIRU

Document.execCommand is deprecated, you should use the Clipboard API instead.

Here you have the vanilla JS example:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Copy to clipboard using JavaScript</title>
    </head>
    <body>
        <h3>Copy To Clipboard using JavaScript</h3>
        <textarea id="comment" rows="5" cols="62"></textarea>
        <br />
        <button type="button">Copy To Clipboard</button>
        <p>
            <strong>Note:</strong>
            Type something in the textarea and click the button to see the
            output.
        </p>
    </body>
    <script>
        const button = document.querySelector("button");
        const textarea = document.querySelector("textarea");

        button.addEventListener("click", event =>
            navigator.clipboard
                .writeText(textarea.value)
                .then(() => alert("Success")),
        );
    </script>
</html>
Enter fullscreen mode Exit fullscreen mode

Cheers!

PS: You should remove #php from the list of tags because you didn't shared any PHP code here, and if you use the example above you can also remove the #jquery tag 🎉