简体   繁体   中英

Select the text and copy to clipboard when focused specific textarea in pure JavaScript?

I have many textareas on my page

<textarea onClick="copyToClipboard(this);">mobile</textarea>
<textarea onClick="copyToClipboard(this);">computer</textarea>
<textarea onClick="copyToClipboard(this);">chair</textarea>
.
.
.

I want to select the text and copy to clipboard when focused that textarea in pure JavaScript without using any library.

My js code is

function copyToClipboard()
{
   this.select(); // I don't know how to select in JavaScript
   document.execCommand("copy");

}

You will get the selected text using window.getSelection() function with pure Javascript.

I've edited the code as per your requirements. To get all the textarea content selected use select() function.

 function copyToClipboard(elem) { console.log(elem.value) elem.focus(); elem.select(); document.getElementById('text').innerHTML = window.getSelection(); document.execCommand("copy"); } 
 <textarea class onClick="copyToClipboard(this)">Computer</textarea> <textarea class onClick="copyToClipboard(this)">Mouse</textarea> <textarea class onClick="copyToClipboard(this)">Keyboard</textarea> <p id="text"></p> 

Try it:

 var el = document.querySelectorAll('textarea'); for (var i = 0; i < el.length; i++) { el[i].addEventListener('click', (e) => { e.target.select(); document.execCommand("copy"); }); } 
 <textarea>mobile</textarea> <textarea>computer</textarea> <textarea>chair</textarea> 

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