最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Copy to clipboard in Javascript having hidden input field - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Mar 9, 2011 at 22:54 AnkitAnkit 1211 silver badge4 bronze badges 1
  • possible duplicate of How to Copy to Clipboard in JavaScript? – Darin Dimitrov Commented Mar 9, 2011 at 22:57
Add a ment  | 

3 Answers 3

Reset to default 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>

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
});

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 (windowscape) { // Mozilla
      try {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        var gClipboardHelper = Components.classes["@mozilla/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;
  }
发布评论

评论列表(0)

  1. 暂无评论