Home / Snippets / How to Copy Text From Textarea Using JavaScript
How to Copy Text From Textarea Using JavaScript cover

How to Copy Text From Textarea Using JavaScript

2.4K

2 years ago

0 comments

To copy text from Textarea input you can make use of the "execCommand(copy)" function. In this short snippet, you will learn how to implement it in Native JavaScript, jQuery as well as AlpineJs.

Copy Textarea Content Using Native JavaScript


To copy the textarea content using native JavasScript you can simply select the textarea using "select()" function and then execute the "copy" command. For the HTML code, it's as simple as the following.
<textarea>Hello world</textarea>

<button>
    Copy
</button>
For the JavaScript logic, you can bind it using a simple "onclick" event like below.
<script>
document.querySelector("button").onclick = function(){
    document.querySelector("textarea").select();
    document.execCommand('copy');
}
</script>

Copy Textarea Content With jQuery


Using jQuery is also really handy, you can have the same HTML markup as above, and then for the on "click" you just attach the code like you normally would.
<script>
$("button").click(function(){
    $("textarea").select();

    document.execCommand('copy');
});
</script>

Copy Textarea Content With AlpineJS


For Alpine JS you can have the textarea with a custom reference and then when the button is clicked you perform the "copy" command.
<div x-data="copyme">
    <textarea x-ref="textarea">Hello world</textarea>

    <button @click="copyTextarea">
        Copy
    </button>
</div>
The whole script to achieve this is as follows.
<script>
document.addEventListener('alpine:init', () => {
    Alpine.data('dropdown', () => ({
        copyTextarea() {
            this.$refs.textarea.select();
            document.execCommand('copy');
        }
    }));
});
</script>

Other Resources

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this