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);
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>
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.