0
<input value="hello" id="p1" readonly style="width: 100%;">
    <br><p>
        <div class="btn-main">Copy!</div>

When visitors press the class "btn-main" I want the input value to be copied to their clipboard.

Michael
  • 41,989
  • 11
  • 82
  • 128
sivert
  • 1

3 Answers3

0

function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
<button id="demo-btn" onclick="copyToClipboard(document.getElementById('demo-btn').innerHTML)">Copy!</button>
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33
0

You may use jQuery clone() Method

Description :- The clone() method makes a copy of selected elements, including child nodes, text and attributes.

$(document).ready(function(){
    $("button").click(function(){
        $("p").clone().appendTo("body");
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Clone all p elements, and append them to the body element</button>

</body>
</html>
Aman Kumar
  • 4,533
  • 3
  • 18
  • 40
0

It can be done like this as well,

document.getElementById("copyBtn").addEventListener("click", function() {
  target = document.getElementById("p1");
  target.focus()
  target.setSelectionRange(0, target.value.length);
  document.execCommand('copy');
});
<input value="hello" id="p1" style="width: 100%;">
<br>
<p>
  <button id="copyBtn" class="btn-main">Copy!</button>

  <textarea></textarea>
  <p> Press Ctrl + V in the text area to see the copied text</p>
Dan Philip Bejoy
  • 4,321
  • 1
  • 18
  • 33