0

i need to copy to clipboard an input text (id=location) from an html form. I am using this code:

const copyToClipboard = str => {
  
  if (navigator && navigator.clipboard && navigator.clipboard.writeText)
    return navigator.clipboard.writeText(str);
  return Promise.reject('The Clipboard API is not available.');
};

From this input:

    <input id="location" type="text" placeholder="Address"/>
    <button onclick="copyToClipboard('location')">Copy</button>

Any ideas? Thanks

Masinos
  • 13
  • 2
  • You are writing the `str` parameter to the clipboard. And in `copyToClipboard('location')` you are passing `'location'` as the parameter, so "location" will be stored in the clipboard. If you want to copy the value in the input field, [you first need to get it](https://stackoverflow.com/questions/11563638/how-do-i-get-the-value-of-text-input-field-using-javascript). – Ivar Feb 15 '22 at 09:49
  • OK, i tried following the 3rd ethod. Now all i get is undefined..still trying/fighting – Masinos Feb 15 '22 at 10:01
  • @Masinos Why the third method? Your `` has an ID. Use that. – Sebastian Simon Feb 15 '22 at 17:30

1 Answers1

1

You are copying to clipboard the world 'location' instead of the input value.

It is possible to access the content of the input using its Id:

document.getElementById("input_id").value;

In your case, to pass the value of the input:

<button onclick="copyToClipboard(document.getElementById('location').value)">Copy</button>
Cubix48
  • 2,607
  • 2
  • 5
  • 17