1

I have an input box where I'm setting the value using jQuery's val() method. I would like to copy to clipboard after setting the value in this textbox. I'm using document.execCommand('copy') but that doesn't seem to work when there is no user action. Is there a different way of solving this?

I set the value in this text after making an AJAX call to the server to fetch a value. Here's what I'm trying to do.

$('#someVal').val('Some text');
el = $('#someVal');
el.focus();
el.select();
document.execCommand("copy", true);
dkulkarni
  • 2,585
  • 4
  • 24
  • 36
  • You might need to use the Flash Alternative as this is sandboxed. – Praveen Kumar Purushothaman Sep 12 '16 at 12:47
  • Possible duplicate of [How do I copy to the clipboard in JavaScript?](http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – skyline3000 Sep 12 '16 at 12:48
  • 1
    Simple way to accomplish use, `clipboard.js` which you can download here. Or else checkout this thread http://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery – David R Sep 12 '16 at 12:48
  • Is there a way of doing this without an additional button to copy to clipboard? – dkulkarni Sep 12 '16 at 12:50

2 Answers2

0

From this answer: https://stackoverflow.com/a/6055620/1201725, (1026 upvotes) The user says: "Automatic copying to clipboard may be dangerous, therefore most browsers (except IE) make it very difficult.". So for the right way, you can use "clipboard.js" like this:

new Clipboard('.btn');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>

<input id="foo" value="same data">
<button class="btn" data-clipboard-target="#foo">
    Copy to clipboard
</button>
Community
  • 1
  • 1
Bahadir Tasdemir
  • 8,208
  • 3
  • 44
  • 55
  • Can I use it without the button? – dkulkarni Sep 12 '16 at 13:06
  • From this answer: http://stackoverflow.com/a/6055620/1201725, (1026 upvotes) The user says: "Automatic copying to clipboard may be dangerous, therefore most browsers (except IE) make it very difficult." so I think that may be impossible, because if you think this was enabled, don't you be angry when a site copies something continuously to your clipboard? – Bahadir Tasdemir Sep 12 '16 at 13:20
0

Think if you follow the following implementation there should be no issues.

$(document).ready(function(){
        $("a#copy-dynamic").zclip({
           path:"ZeroClipboard.swf",
           copy:function(){return $("input#dynamic").val();}
        });
    });

Also, for further reference visit: http://www.phpgang.com/how-to-copy-text-to-clipboard-using-jquery_501.html

Abhinav Ralhan
  • 309
  • 1
  • 2
  • 11