2

I have a span which shows the name of the user like this and a hidden input box which contains username of the user. The input box sits right below the span on UI and has visibility hidden

<span> My Name </span>
<input type = "text" class = "hidden" value = "MyUserName"> 

What I want is when the user clicks on the visible span and presses Ctrl + C, I want the value of the input box to get copied on the clipboard. (MyUserName in this case). Is there any way I can do this in Javascript?

Ankit
  • 111
  • 1
  • 3
  • possible duplicate of [How to Copy to Clipboard in JavaScript?](http://stackoverflow.com/questions/400212/how-to-copy-to-clipboard-in-javascript) – Darin Dimitrov Mar 09 '11 at 22:57

3 Answers3

3

try this

<span onClick="CopyToClipboard()"> My Name </span>
<input type = "text" id="test" class = "hidden" value = "MyUserName">

then a script

<script type="text/javascript">

function CopyToClipboard()

{

document.getElementById('test').focus();

document.getElementById('test').select(); 

}

</script>
Trevor Rudolph
  • 1,025
  • 4
  • 18
  • 40
  • That worked like a charm !! Simple and very efficient solution. I don't even need to use flash.. Thanks a ton.. – Ankit Mar 10 '11 at 00:46
  • I had the same problem in a different situation but i just needed to change it a little. – Trevor Rudolph Mar 10 '11 at 00:48
  • @Ankit you know that if someone gives you the correct answer you click the outline of the check next to the answer to say "thats the one that helped me and my question is solved" – Trevor Rudolph Apr 01 '11 at 01:39
0

Take a look here: Handling Keyboard Shortcuts in Javascript. The author has created a library of Javascript functions that make it easy to do what you're asking.

With this script library, you can do something like:

shortcut.add("Ctrl+C",function() {
    //Do something here
});
NakedBrunch
  • 45,899
  • 13
  • 69
  • 97
0

I have this handy functions that works for IE and Firefox (ask a permission). For others though you need zeroclipboard flash control.

When it cannott work, it displays a prompt with text focused so user can Ctrl+c the data

function copyText(text) {
    if (window.clipboardData) { // Internet Explorer
      window.clipboardData.setData("Text", ""+ text);  
    } else if (window.netscape) { // Mozilla
      try {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        var gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
        gClipboardHelper.copyString(text);
      } catch(e) {
          return prompt("Ctrl+C this text : ", text);
      }
    } else {
      return prompt("Ctrl+C this text : ", text);
    }
    return false;
  }
jujule
  • 9,806
  • 3
  • 39
  • 59