Solution 1 :

I’m not sure if this is duplicate because this is a more specific question, but How do I copy to the clipboard in JavaScript? has various solutions for copying to the clipboard, including the execCommand approach.

Scroll down to Complex Example: Copy to clipboard without displaying input, which suggests fixing the Input or Textarea in the upper left corner with essentially no height, width, border, etc. so that it is not visible.

Problem :

I am making a password creator script, in which I don’t want to show the generated password, but only copy the generated password to clipboard.

I have script for achieving the aforementioned functionality as below:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <button type="button" onclick="alert(generatePassword())">Generate Password</button>
        <script type="application/x-javascript">
        function generatePassword() {
            var length = 15,
                charset1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
                charset2 = "[email protected]#$%^&",
                charset3 = "[email protected]#$%^&*()!+=~",
                retVal = "";
            for (var i = 0, n = charset3.length; i < length; ++i) {
                retVal += charset3.charAt(Math.floor(Math.random() * n));
            }
            copyToClipboard2(retVal);
            return 'Password ready to be pasted';
        }
        const copyToClipboard2 = str => {
            const el1 = document.createElement('input');
            el1.setAttribute('type','text');
            // el1.setAttribute('type','hidden');
            el1.value = str;
            document.body.appendChild(el1);
            el1.select();
            document.execCommand('copy');
            document.body.removeChild(el1);
        };
        </script>
    </body>
</html>

Notice the commented out line, I have commented it because it is not working.

So as I have already mentioned in question, how do I make use of on-the-fly created hidden input field to temporary store the password before copying to clipboard, with the same code as above ?

Comments

Comment posted by vch

What you are doing with text element (some people use textarea instead) seems just about fine. Hidden field is not a text field, so its content cannot be “selected” using

By

Leave a Reply

Your email address will not be published. Required fields are marked *