I've actually seen a few questions about this, most of them are from at least 5 or 6 years ago.
I want to have an input box:
<input id="copy-text" type="text" value="Click this text!">
Here's the JavaScript I've been trying to work with:
document.getElementById("copy-text").onclick = function() {
this.select();
execCommand('copy');
alert('This is a test...');
}
I know my code doesn't work. If I remove execCommand('copy');
then the alert()
pops up, but it seems to be hitting an error at that line. I've tried making it this.execCommand('copy');
as well, not really sure what to do here.
Fiddle: https://jsfiddle.net/6v24k4sk/
The idea is that I want the user to click the input box, it will select all the text, and then copy it to the clipboard.
Any ideas?
Description. The onclick property of an Input object specifies an event handler function that is invoked when the user clicks on the input element. It is not invoked when the click( ) method is called for the element. Only form elements that are buttons invoke the onclick event handler.
The HTMLInputElement. select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.
It is pretty simple to select whole text on just a single click. You can use the following JavaScript code snippet: <!DOCTYPE html> <html> <head> <title> Title of the Document </title> </head> <body> <div> Input Text: <input onClick="this.select ();" type="text" value="Sample Text"> </div> </body> </html>. Try it Yourself ».
Click on the button to copy the text from the text field. Copy to clipboardCopy text Copy Text to Clipboard Step 1) Add HTML: Example The text field --> <input type="text" value="Hello World" id="myInput"> The button used to copy the text --> <button onclick="myFunction()">Copy text</button> Step 2) Add JavaScript:
Copy Text to Clipboard Step 1) Add HTML: Example The text field --> <input type="text" value="Hello World" id="myInput"> The button used to copy the text --> <button onclick="myFunction()">Copy text</button> Step 2) Add JavaScript:
Note: When you consider onclick="this.select()", At the first click, All characters will be selected, After that maybe you wanted to edit something in input and click among characters then it will select all characters again.
You should put a document. in front of the execCommand.
document.getElementById("copy-text").onclick = function() {
this.select();
document.execCommand('copy');
alert('This is a test...');
}
Here you can find a working example: https://jsfiddle.net/9q3c1k20/
edit:
The function also returns whether this functionality is supported in the browser. I think you should check the value, because execCommand still has no final specification and is therefore not guaranteed to work in all browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With