In this tutorial, I will show you how to copy text to the clipboard on a button click using jQuery from a textbox.
It’s very helpful for the users to click a button to copy everything in a textbox, instead of selecting and copying using the Mouse.
So today’s tutorial, we will have a textbox and a clickable copy button in a form.
Javascript
We create a false textarea element in the DOM, which you will not see it anywhere on the page. Next, we will assign the real value from our textbox to this virtual textarea. In this case, we pass the textbox value as a parameter of the function doCopyToClipboard
. As a result, we will have our text copied to the clipboard by the command document.execCommand( 'copy' )
. As soon as we are done with the process we will remove the textarea from the page.
function doCopyToClipboard(text) { var textArea = document.createElement( "textarea" ); textArea.value = text; document.body.appendChild( textArea ); textArea.select(); try { var successful = document.execCommand( 'copy' ); console.log('Copying text command was ' + msg); } catch (err) { console.log('Oops, unable to copy',err); } document.body.removeChild( textArea ); }
The next function will be our click event which I wrote in jQuery to demonstrate how it works in jQuery. However, you can write this in pure JavaScript as well.
$( '#btn_copy' ).click( function() { clipboardText = $( '#textbox1' ).val(); copyToClipboard( clipboardText ); alert( "Copied to Clipboard! Now paste to wherever you need!" ); });
HTML
<div> <input type="text" class="form-control" id="textbox1"> <button type="button" class="btn" id="btn_copy">Copy</button> </div>
In conclusion, we have our feature for copying text value from textbox to clipboard.
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply