I am trying to copy some text to clipboard in a web page. I set a textbox, with its display set to "none" and populate it with some text. Then when I button is clicked, I try to set the clipboard to its content but I keep getting null.
I tried two ways of setting the clipboard: set the value of a hidden field "hfCTC" and calling ShowCTC2() and setting the value of input "ToCopy" and calling ShowCTC() and the alert shows null in both cases.
I don't want the button to do a postback, so I return false in js functions.
<input type="text" id="ToCopy" style="display:none" />
<asp:HiddenField runat="server" ID="hfCTC" />
<input type="image" id="ibCTC" src="images/CTC.png" onclick="return ShowCTC();" />
function ShowCTC2(){
if (document.all) // IE only
{
if (window.clipboardData && clipboardData.setData)
{
var ctrl = document.getElementById('<%=hfCTC.ClientID %>');
var textToCopy = ctrl.value;
window.clipboardData.setData('Text', ctrl.text);
alert (window.clipboardData.getData ('Text'));
}
}
return false;
}
function ShowCTC(){
if (document.all) // IE only
{
window.clipboardData.clearData ("Text");
select_all();
alert (window.clipboardData.getData ('Text'));
}
return false;
}
function select_all() {
var text_val = document.getElementById('ToCopy');
text_val.focus();
text_val.select();
if (!document.all) return; // IE only
r = text_val.createTextRange();
r.execCommand('copy');
}
If I comment out the clearing of clipboard line in ShowCTC() and do a manual Ctl-C to copy something, the alert shows what I copied but the setting of clipboard data through code seems to fail.
This post solved the issue:
MSIE and addEventListener Problem in Javascript?.
I changed the code to the following: