简体   繁体   中英

Copy text from textarea to clipboard - Python

I'm trying to enable a Copy button that will copy the content from the textarea, I gave an example of my HTML file and JS, I tried in all ways but I didn't succeed. Thanks for your help.

My HTML

    {% if trans != "" %}
    <br>
        <div id="sTransContainer">
            <h1>Trans</h1>
            <textarea style="resize:none" cols="5" rows="10" id="sText">{{ trans }}</textarea>
            <div class="right btn-group">
                <button onclick="myFunction()">Copy text</button>
                <script async src="js/copy.js"></script>
            </div>
        </div>
    {% endif %}

My copy.js

function myFunction() {
  var copyText = document.getElementById("trans");
  copyText.select();
  copyText.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}

just switch trans with sText

 function myFunction() { var copyText = document.getElementById("sText"); copyText.select(); copyText.setSelectionRange(0, 99999) document.execCommand("copy"); alert("Copied the text: " + copyText.value); }
 <div id="sTransContainer"> <h1>Trans</h1> <textarea style="resize:none" cols="5" rows="10" id="sText">{{ trans }}</textarea> <div class="right btn-group"> <button onclick="myFunction()">Copy text</button> <script async src="js/copy.js"></script> </div> </div>

You can also use navigator.clipboard . https://developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard

 function copyToClipboard() { let clip = navigator.clipboard; if (clip === undefined) { console.log( "Upgrade your browser to use the clipboard feature.", ); } else { navigator.clipboard.writeText(document.getElementById('my_input').value); } }
 <input id='my_input' /> <button onClick='copyToClipboard()' > Click me </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