1

if I comment the line 1 and uncomment the line 2, this code works. What is the problem with the prompt?

let parte = prompt("What is your name?"); //line 1
//let parte = "Batman"; // line 2
let documents = "bla bla bla";
let $dummy = $("<input>");

$dummy.attr("value",  parte+ " " + documents);
$("body").append($dummy);
$dummy.select();
document.execCommand("copy");
$dummy.remove();
Thiago
  • 11
  • 3

1 Answers1

0

.execCommand() Needs to be in an Event Handler

Use .val() for form controls but .attr() will work as well. In the demo the rest of your code will not work without an event handler. Refer to Using .execCommand();.

Demo

Details commented in demo

let parte = prompt("What is your name?");
let documents = "bla bla bla";
let $dummy = $("<input>");

// Use .val() for input values is better either one will work.
$dummy.val(parte + " " + documents);
//$dummy.attr("value", parte+ " " + documents);
$("body").append($dummy);

// You need to make an event handler
function copy() {
  $dummy.select();
  document.execCommand("copy");
  $dummy.remove();
}
$('.copy').on('click', copy);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button class='copy'>Copy</button>

<fieldset class='edit' contenteditable>
  Paste Here
</fieldset>
Community
  • 1
  • 1
zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • jQuery.fn.select is a default method and as long as the input has not been appended to the doc, `attr()` should also work. https://jsfiddle.net/4oLn9k5p/ – Kaiido Feb 19 '19 at 06:24
  • Thanks for the answers, guys. – Thiago Feb 20 '19 at 18:05
  • I would like to know if there is any way to make this code work without having to click the button. – Thiago Feb 20 '19 at 18:10
  • You click click anything you register an event on as long as `execCommand()` is inside an event handler. If you want to programmatically accomplish the task then `execCommand()` isn't the right kind of method to use since it requires user interaction. – zer00ne Feb 21 '19 at 09:05