简体   繁体   中英

JavaScript copy textarea value to clipboard not working

I am trying to use javascript to copy the contents of a textarea to clipboard and its not working. When I check the clipboard its empty. My Javascript is:

 function copyStudentEmails() { /* Get the text field */ var copyStudentEmail = document.getElementById("student-emails"); /* Select the text field */ copyStudentEmail.select(); copyStudentEmail.setSelectionRange(0, 99999); /* For mobile devices */ /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ alert("Copied student emails to clipboard"); }
 <textarea rows="5" id="student-emails" class="form-control" disabled required>@studentEmails</textarea> <button class="btn btn-primary" onclick="copyStudentEmails()">Copy</button>

The contents of the textarea are visible but the copying is not working. The alert at the end of the javascript function is displayed but the clipboard is empty.

It is advisable to use camel casing for ids. Try the below

    document.querySelector("textarea").select();
    document.execCommand('copy');

Also, remove the disabled property from your text area.

It works if you omit the disabled attribute:

 function copyStudentEmails() { /* Get the text field */ var copyStudentEmail = document.getElementById("student-emails"); /* Select the text field */ copyStudentEmail.select(); copyStudentEmail.setSelectionRange(0, 99999); /* For mobile devices */ /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ alert("Copied student emails to clipboard"); }
 <textarea rows="5" id="student-emails" class="form-control" required>@studentEmails</textarea> <button class="btn btn-primary" onclick="copyStudentEmails()">Copy</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM