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.
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.
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>