Amadeus
Amadeus

Reputation: 13

Copy text from ONE of SEVERAL inputs with a SINGLE function (by ID)

everyone. Working on this HTML document.

I have a function (triggered by a button) that selects and copies the text from an input. Said function works based on the input's ID.

I want to add several inputs and fix the function to get the text of ONE specific input, but so far, I have only been able to make it work by stating the specific ID of ONE input.

Obviously, I don't want to implement a function for every input I will use.

This is my current code:

<input type="text" value="AWESOME TEXT" id="1">   

<button id="1" onclick="myFunction()"> Copy</button>

And here is the script

<script>

function myFunction() {

  var copyText = document.getElementById("1");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}

</script>

The function finds the input with the ID "1" and copies the text. Because I have to sate the "1", it only works with that specific input.

I have tried with:

  var copyText = document.getElementById(this.id);

and with:

  var copyText = document.innerHTML);

but to no avail.

So far, my only option is to wirte a function for every input, but not only will this be burdensome and unpractical. It will also bloat my code.

Thanks in advance.

Upvotes: 1

Views: 558

Answers (2)

Amadeus
Amadeus

Reputation: 13

It worked like a charm.

I hadn't noticed that the button ID must also match the input id.

Thanks a lot.

That was really fast and more than helpful, Pietro Nadalini.

Upvotes: 0

Pietro Nadalini
Pietro Nadalini

Reputation: 1800

If you send the id as a parameter it will work properly. You can do it like this:

function myFunction(myId) {
  var copyText = document.getElementById(myId);
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
<input type="text" value="AWESOME TEXT" id="1">   

<button id="1" onclick="myFunction(this.id)"> Copy</button>

Upvotes: 1

Related Questions