Click here to Skip to main content
15,887,398 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i write this code to copy textareas content with unique button but i have a problem that only the first textarea is copied

HTML
<pre><body>


<textarea class="form-control" tabindex="0">something</textarea>
 <button  onclick="myFunction()">clickme</button>
<textarea class="form-control"tabindex="3" >something1</textarea>
 <button  onclick="myFunction()">clickme</button>
<textarea class="form-control" >something2</textarea>

  <button onclick="myFunction()">clickme</button>
  


  <script>
   var copyText = document.getElementsByClassName("form-control")[0];
 function myFunction() {

		
  // Get the text field
 

  // 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);
  
  ///second
  
  
} 
  </script>
</body>


but the button copy tthe first textarea only

You can try the code and you understand my problem
Thanks a lot

What I have tried:

copy first textarea button issue
Posted
Updated 30-Nov-22 1:08am

1 solution

You need to get the reference to the element you want to copy from within the event handler.

Based on the markup in this copy of the question, the element is the immediate preceding sibling of the button; therefore:
HTML
<textarea class="form-control" tabindex="0">something</textarea>
<button type="button" class="copy-button">clickme</button>
<textarea class="form-control"tabindex="3" >something1</textarea>
<button type="button" class="copy-button">clickme</button>
<textarea class="form-control" >something2</textarea>
<button type="button" class="copy-button">clickme</button>
JavaScript
document.addEventListener("click", e => {
    let button = e.target;
    if (button.tagName !== "BUTTON") { button = button.closest("button"); }
    if (!button || !button.classList.contains("copy-button")) { return; }
    
    e.preventDefault();
    
    let textarea = button.previousElementSibling;
    while (textarea && textarea.tagName !== "TEXTAREA") {
        textarea = textarea.previousElementSibling;
    }
    
    if (!textarea) {
        alert("Unable to find the textarea to copy!");
        return;
    }
    
    textarea.select();
    textarea.setSelectionRange(0, 99999);
    document.execCommand("copy");
    alert(`Copied the text: ${textarea.value}`);
});
Demo[^]
 
Share this answer
 
Comments
Red Kipling 30-Nov-22 7:22am    
thx a lot for help
this is what i want

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900