0

Suppose I have a list of the following HTML elements with a Javascript event to copy the content of the HTML input type text into the clipboard:

<input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>

etc..

How do I copy the txt using javascript?

I am trying to tweak the code below but I can't figure out how to pass the HTML id to the javascript code. I know the getElementById() is not correct in that context and shouldn't be called. But I don't know how to carry the id value across into the Javascript function.

<script>
function CopyToClipboard(myInput) {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select(myInput);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
</script>

Any help would be greatly appreciated.

Thank you

2 Answers 2

1

The error is that you use document.getElementById("myInput") instead of document.getElementById(myInput).

Sign up to request clarification or add additional context in comments.

2 Comments

I see! wasn't sure if it that function was refering to the variable itself or just its name. I didn't think much of it because I thought getElementById() was maybe not the right function to use in this context.Thank you.
@Bluz You're welcome! By the way, you do not need to pass any arguments to the select() function, so just use copyText.select().
0

function CopyToClipboard(myInput) {
  /* Get the text field */
  var copyText = document.getElementById(myInput) // pass dynamic value here

console.log(copyText)
  /* Select the text field */
  copyText.select(myInput);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
<input type="text" size="70" value="something1" id="v1">
<button onclick="CopyToClipboard('v1')">Copy command</button>

<input type="text" size="70" value="something2" id="v2">
<button onclick="CopyToClipboard('v2')">Copy command</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.