简体   繁体   中英

How do you copy text to clipboard by clicking a button

I am trying to make a single button which copies text to the clipboard, but I am am having trouble. It is copying the wrong thing.

Essentially, I have a variable called my_fav_food . Then I have a button called My Fav Food . When I click this button, it calls the function copying_function and parses in the my_fav_food variable into the function. Then the function automatically copies the text to the clipboard.

<!DOCTYPE html>
<html>
<body>
<script>
var my_fav_food = "My fav food is pizza"
</script>

<button onclick="copying_function(my_fav_food)">My Fav Food</button>

<script>
function copying_function(string) {
  string.select();
  document.execCommand("string");
}
</script>

</body>
</html>

The select() method can only be used to select the contents of a text field. You cannot use it the way you are using it now.

You could try: https://clipboardjs.com/

Or you might try a hack to put the text in a hidden text area (I don't guarantee this would work)

You need to create a DOM element and set the string to it then do the selection programmically. As you're not appending the element to the DOM, it will not be visible in the view.

 <!DOCTYPE html> <html> <body> <script> var my_fav_food = "My fav food is pizza"; </script> <button onclick="copying_function(my_fav_food)">My Fav Food</button> <script> function copying_function(string) { // string.select(); const el = document.createElement('textarea'); el.value = string; document.body.appendChild(el); el.select(); document.execCommand('copy'); console.log("The data copied successfully! press `ctrl+v` to see output"); document.body.removeChild(el); } </script> </body> </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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM