I want to copy a card number into the clipboard so that I can paste it in Notepad. The code which I got from the internet works very well if tried in the developer toolbar o
Updated:
User interaction is mandatory to execute document.execCommand
.
So in your case it is not possible to copy the text from AJAX Response. It is the security measure that browsers agreed upon.
Refer W3C API
Copy and cut commands triggered through a scripting API will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this.
A workaround with user interaction
Steps added:
document.execCommand
since you are directly interacting with browser (Hence no security issue as mentioned in API
)$(document).ready(function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com' + '/posts/1',
method: 'GET'
}).then(function(data) {
console.log(data);
$('#toBeCopied').val(data.title);
$("#copyIt").attr('disabled', null);
});
});
function copyToClipboard(){
var $temp = $("");
$("body").append($temp);
$temp.val($("#toBeCopied").val()).select();
var result = false;
try {
result = document.execCommand("copy");
} catch (err) {
console.log("Copy error: " + err);
}
$temp.remove();
}
Below button will be enabled once the data is available from AJAX