-1

I have copied the div element to the alert box. Now when I pressed ok button is it possible the text is copied to the user's clipboard.

Here is the code for reference:

$(document).ready(function(){
    $("#bn").click(function(event){
        $(alert($('#demo').text())
    });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • If you would like to only copy the text depending on the clients response to the alert than maybe `confirm()` would be better as shown in this example [**JsFiddle demo**](https://jsfiddle.net/ogyjsby5/) – NewToJS May 18 '18 at 07:25

2 Answers2

1

select(); to Select the text field and document.execCommand("copy"); to Copy the text inside the text field.

$(document).ready(function(){
    $("#bn").click(function(event){
        var valueToCopy = $('#demo').text();
        $('#demo').append('<textarea id="temp"></textarea>');
        $("#temp").val(valueToCopy);
        $('#temp').select().text();
        document.execCommand("Copy");
        $("#temp").remove();
        $(alert(valueToCopy));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo"> Hello java<br> Welcome to the world of programming<br> Error generated<br> Correction alert<br> </div> <div> <input type="button" value="clickToCopy" id="bn"> </div>
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
-2

Yes it is possible.

In your html file include the below code.

<input type="text" value="Hello World" id="myInput">
<button onclick="myFunction()">Copy text</button>

In your js file include the below code.

<script>
function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

For reference please visit the below link .

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_copy_clipboard

Hope this will resolve your issue .

gaurav patni
  • 45
  • 1
  • 8