Copying to clipboard textbox value using jQuery/JavaScript
Asked Answered
M

5

8

I have a textbox & button which looks like this:

     <div class="col-xs-11" style="padding:20px 0 ">
     <input type="text" class="form-control txtKeywords" id="txtKeyw" style="margin-bottom:10px; height:45px;" maxlength="80" placeholder="Click on keywords to combine your title">
   <button type="submit" class="btn btn-space btn-success btn-shade4 btn-lg copyToClipboard">
    <i class="icon icon-left s7-mouse"></i> Copy to Clipboard
     /button>

And when the user clicks the button copy to clipboard, I'd like to copy the contents of the textbox into the clipboard like this:

$(document).on("click", ".copyToClipboard", function () {
    copyToClipboard("txtKeyw");
    successMessage();
});

Where the definition of the copyToClipboard function is:

 function copyToClipboard(element) {
            var $temp = $("<input>");
            $("body").append($temp);
            $temp.val($(element).text()).select();
            document.execCommand("copy");
            $temp.remove();
        }

But when I do this, nothing happens -- no values are copied to clipboard from the textbox... What am I doing wrong here?

MORE INFORMATION:

  • This happens in both Chrome 59 64-bit and Firefox 54 32-bit.
  • successMessage() is called and displayed in the browser.
  • Adding # in front of the element's ID does not resolve the issue.
Mighell answered 3/7, 2017 at 15:5 Comment(7)
@zuluk i tested in chrome + firefox , none worked :/Mighell
Chrome 43 or greater and Firefox 41 or greater?Giblets
Does successMessage() get called? Does copyToClipboard() run?Gelid
@Gelid yes i can verify success message gets called and it's displayed in browser ...Mighell
@Giblets Version 59.0.3071.115 (Official Build) (64-bit), Firefox: 54.0.1 (32-bit)Mighell
Looks like you need to put a # before the "txtKeyw" when you pass it into your function.Gelid
@Gelid tried with # as well doesn't works...Mighell
G
14

STEP 1: Change your copyToClipboard(element) like this:

function copyToClipboard(text) {

   var textArea = document.createElement( "textarea" );
   textArea.value = text;
   document.body.appendChild( textArea );       
   textArea.select();

   try {
      var successful = document.execCommand( 'copy' );
      var msg = successful ? 'successful' : 'unsuccessful';
      console.log('Copying text command was ' + msg);
   } catch (err) {
      console.log('Oops, unable to copy',err);
   }    
   document.body.removeChild( textArea );
}

STEP 2: Give an id to your button and then add an event listener to it like this:

$( '#btnCopyToClipboard' ).click( function()
 {
     var clipboardText = "";
     clipboardText = $( '#txtKeyw' ).val(); 
     copyToClipboard( clipboardText );
     alert( "Copied to Clipboard" );
 });
Gavingavini answered 3/7, 2017 at 16:3 Comment(6)
It displays in log that copy was successsful ... but... when i try to paste text nothing is there ;/Mighell
Instead of: $( #txtKeyw ).text() was required $( #txtKeyw ).val()Mighell
Quotes are needed around #txtKeyw, no?Gelid
I have edited the answer based on comments. Sorry, I didn't try it myself but hopefully my answer gave an idea on how this should beGavingavini
Works fine. Just a minor typo error in the code: the first function name has to be renamed from copyToClipboard to copyTextToClipboard. Thanks!Meyerhof
@Mighell I know this is old, but did you ever get this working? The approved answer doesn't work for me. Nearly exactly the same scenario.Policewoman
O
2

Try this..this is the correct way.

Step 1:

function copyToClipboard(text) {

   var textArea = document.createElement( "textarea" );
   textArea.value = text;
   document.body.appendChild( textArea );

   textArea.select();

   try {
      var successful = document.execCommand( 'copy' );
      var msg = successful ? 'successful' : 'unsuccessful';
      console.log('Copying text command was ' + msg);
   } catch (err) {
      console.log('Oops, unable to copy');
   }

   document.body.removeChild( textArea );
}

Step 2:

$( '#btnCopyToClipboard' ).click( function()
 {
     var clipboardText = "";

     clipboardText = $( '#txtKeyw' ).val();

     copyToClipboard( clipboardText );
     alert( "Copied to Clipboard" );
 });
Ormandy answered 18/9, 2017 at 0:24 Comment(0)
M
1

copyToClipboard() get a element as parameter. txtKeyw is id and you must put # before it.

Microelement answered 3/7, 2017 at 15:30 Comment(0)
G
0

I believe that document.execCommand('copy') is deprecated now, tested on Edge v 113.0 and Opera v 98.0

Use this instead:

function copyToClipboard() {
  var txtField = document.getElementById('txt-field');
   txtField.select();
   navigator.clipboard.writeText(txtField.value);
  alert('Copied to clipboard!');
}
Garris answered 10/5, 2023 at 3:15 Comment(0)
S
0

I preffer this code to copy textbox all text using jquery.

HTML CODE
<input type="text" class="form-control" id="ddlTextBox" />
<button type="button" id="btnSave">Copy Text</button>

JS CODE
$('#btnSave').click(function () {     navigator.clipboard.writeText($('#ddlTextBox').val());
});

Shiff answered 12/7 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.