Search code examples
javascripthtmlclipboard

How to combine multiple Copy to Clipboard Functions?


I'm trying to figure out how to copy multiple Copy to Clipboard buttons into a single script.

My page has dynamic text areas that are filled out as the user completes the form and each textarea has its own copy to clipboard button:

function CopyTemplateField1() {
  var copyText = document.getElementById("TemplateField1");
  copyText.select();
  navigator.clipboard.writeText(copyText.value);
}

function CopyTemplateField2() {
  var copyText = document.getElementById("TemplateField2");
  copyText.select();
  navigator.clipboard.writeText(copyText.value);
}

function CopyTemplateField3() {
  var copyText = document.getElementById("TemplateField3");
  copyText.select();
  navigator.clipboard.writeText(copyText.value);
}
<tr>
  <td><textarea id="TemplateField1"></textarea></td>
  <td><img src="copybutton.png" onClick="CopyTemplateField1();"></td>
</tr>

<tr>
  <td><textarea id="TemplateField2"></textarea></td>
  <td><img src="copybutton.png" onClick="CopyTemplateField2();"></td>
</tr>

<tr>
  <td><textarea id="TemplateField3"></textarea></td>
  <td><img src="copybutton.png" onClick="CopyTemplateField3();"></td>
</tr>

I still want each copy button to copy the text from the associated textarea but have the three separate functions combined into one function that will differentiate between which button is pressed and copy that text to the clipboard.

I tried using if/else but kept giving errors. Searched for similar articles but couldn't find anything that matched. If there is another method to use but prefer to stay with JavaScript as the page is pretty simplistic.


Solution

  • Using function parameters seems to be the best option

    <tr>
      <td><textarea id="TemplateField1"></textarea></td>
      <td><img src="copybutton.png" onClick="CopyTemplateField(1);"></td>
    </tr>
    
    <tr>
      <td><textarea id="TemplateField2"></textarea></td>
      <td><img src="copybutton.png" onClick="CopyTemplateField(2);"></td>
    </tr>
    
    <tr>
      <td><textarea id="TemplateField3"></textarea></td>
      <td><img src="copybutton.png" onClick="CopyTemplateField(3);"></td>
    </tr>
    
    function CopyTemplateField(n) {
      var copyText = document.getElementById("TemplateField" + n);
      copyText.select();
      navigator.clipboard.writeText(copyText.value);
    }