2

I want to copy input to my clipboard using javascript so is there any way I can do,Thanks

WITHOUT MAKING AN INPUT FIELD

JavaScript And HTML

function copy(input){
  
}
<p>Text To Copy = hi <button type="button" onclick="copy('hi')">click to copy</button></p>
Kingslayer47
  • 312
  • 12
  • No, cause I don't want to create a textarea and all solutions there are by creating a textarea "I Think" – Kingslayer47 Oct 19 '20 at 07:19
  • `navigator.clipboard.writeText(text)` does not use a text area. The [clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) is the modern approach for interacting with the clipboard. This is described in the accepted answer. – VLAZ Oct 19 '20 at 07:53

3 Answers3

2

You can use navigator.clipboard.writeText to copy the text to clipboard.

function copy(input) {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(input).then(() => {
      console.log('Copied to clipboard successfully.');
    }, (err) => {
      console.log('Failed to copy the text to clipboard.', err);
    });
  } else if (window.clipboardData) {
    window.clipboardData.setData("Text", input);
  }
}
<p>Text To Copy = hi <button type="button" onclick="copy('hi')">click to copy</button></p>
Derek Wang
  • 9,675
  • 4
  • 14
  • 36
2

Please try this. Maybe it will work for you.

 function myFunction() {
      /* Get the text field */
      var copyText = document.getElementById("myInput");
    
      /* Select the text field */
      copyText.select();
      copyText.setSelectionRange(0, 99999); /*For mobile devices*/
    
      /* Copy the text inside the text field */
      document.execCommand("copy");
    
      /* Alert the copied text */
      alert("Copied the text: " + copyText.value);
    }
 <input type="text" value="Hello World" id="myInput">
    <button onclick="myFunction()">Copy text</button>

   
CodeBug
  • 1,156
  • 1
  • 5
  • 18
Rishi Purwar
  • 956
  • 2
  • 7
  • 13
1

function copy_text_fun() {
    //getting text from P tag
    var copyText = document.getElementById("copy_txt");  
    // creating textarea of html
    var input = document.createElement("textarea");
    //adding p tag text to textarea 
    input.value = copyText.textContent;
    document.body.appendChild(input);
    input.select();
    document.execCommand("Copy");
    // removing textarea after copy
    input.remove();
    alert(input.value);
}
<p id="copy_txt">hi</p>
<button  onclick="copy_text_fun()">Copy</button>

here is with the paragraph tag,

CodeBug
  • 1,156
  • 1
  • 5
  • 18