Posts Learn Components Snippets Categories Tags Tools new About
/

How to Copy Text From Textarea Using JavaScript

Learn how to copy text content from Textarea input in JavaScript using native JavaScript function the easy way

Created on Nov 12, 2021

5 views

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

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

)