Solved

button to select & copy

Posted on 2011-09-21
9
314 Views
Last Modified: 2012-06-21
Hi experts,

I'm after a button that will copy an item from an asp:repeater to clipboard, the process must be infinitely repeatable so that the user can return and copy something else as many times as they wish.
I don't want the user to have to manually select the text on screen I want the button to do the selecting and copying in one hit.

Is this possible, i'm thinking there could be an indexing issue here given that the text I want is dynamic...



0
Comment
Question by:forsters
9 Comments
 
LVL 40

Assisted Solution

by:gurvinder372
gurvinder372 earned 250 total points
Comment Utility
0
 
LVL 16

Expert Comment

by:Easwaran Paramasivam
Comment Utility
Below code is used to copy the given content into Clipboard. Convert the repeater content into HTML using rendercontrol method and pass the content to the javascript function.
function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		user_pref("signed.applets.codebase_principal_support", true);
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;

		// create a transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;

		// specify the data we wish to handle. Plaintext in this case.
		trans.addDataFlavor('text/unicode');

		// To get the data from the transferable we need two new objects
		var str = new Object();
		var len = new Object();

		var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

		var copytext=meintext;

		str.data=copytext;

		trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

		var clipid=Components.interfaces.nsIClipboard;

		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);	   
	}
}

Open in new window

0
 

Author Comment

by:forsters
Comment Utility
Hi, thanks I should perhaps revise the question; I can get the javascript to select and copy but I think because the items are in a repeat region it defaults to selecting the first item in the list:

So for example if I have a list of numbers 1 - 10 that I'm displaying from a datatable in my repeat region, when I add the button code I have ten buttons one for each number (because they too are in the repeat region) but my buttons don't know which number in the list they refer to.. so whatever button I click it just takes the first item (number 1) is there a way round this? So that the buttons know that the data is dynamic, normally this would involve referring to the items by their index - so 1 would have an index of 0  but i'm not sure how i'd work that into the javascript. The rest of the page is asp.net using VB.
0
 

Author Comment

by:forsters
Comment Utility
EaswaranP thanks for your post, can you show me what you mean by the rendercontrol method, I'm not familiar...

I attach the repeater code as it stands and have amended my script to the code you posted
<ASP:Repeater runat="server" DataSource='<%# Data.DefaultView %>' >
            
              <ItemTemplate>
  
              <tr>
                            <td><pre id="pre"><%# Data.FieldValue("Title", Container) %></pre></td>
              <td><button id="copy" onclick="copyToClipboard(document.getElementById('pre').innerHTML)">Copy</button>
</td>
                            </tr>
             
              </ItemTemplate>
            </ASP:Repeater>

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 17

Assisted Solution

by:sonawanekiran
sonawanekiran earned 250 total points
Comment Utility
Use jquery
$(document).ready(function(){
  $('#copy').click(function(){
   var htm =  $(this).closest('tr').find("pre").html();
    copyToClipboard(htm);
  });
});

Open in new window

0
 
LVL 17

Expert Comment

by:sonawanekiran
Comment Utility
And remove onclick even i.e. onclick="copyToClipboard(document.getElementById('pre').innerHTML)". So your button html will be

<button id="copy">Copy</button>
0
 

Author Comment

by:forsters
Comment Utility
Hi Sonawanekiran

Many thanks, I can't get that to work for me I'm afraid, it doesn't appear to copy anything as when I come to paste I'm just pasting the last item that was copied to my clipboard.

Had I got it to work my next question would have been what If I have more than one item in my <tr> - which I do, I just stripped it down to one for simplicity...
0
 

Accepted Solution

by:
forsters earned 0 total points
Comment Utility
For anyone else trying to do this, my final working code is as follows:
<!------------------------------aspx page---------------------------------------->

 <asp:GridView ID="GridView1" DataSourceID="Passwords" Width="740px" BorderStyle="None" AutoGenerateColumns="false" GridLines="Horizontal" onrowdatabound="GridView1_RowDataBound" EmptyDataText="There are currently no passwords saved under your name" runat="server">
    <Columns>
    <asp:HyperLinkField  DataTextField="SiteName" DataNavigateUrlFields="SiteURL" Target="_blank" ItemStyle-Width="150px" HeaderStyle-HorizontalAlign="Left" SortExpression="SiteName"/>
     <asp:TemplateField HeaderText="Username" ItemStyle-Width="100px" HeaderStyle-HorizontalAlign="Left">
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("UserName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

   
    <asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-Width="80px">
                        <ItemTemplate>
                            <asp:Button ID="Button1" runat="server" Text="Copy" />
                        </ItemTemplate>
                    </asp:TemplateField>

    <asp:TemplateField HeaderText="Password" ItemStyle-Width="100px" HeaderStyle-HorizontalAlign="Left">
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Eval("Password") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

   
    <asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-Width="80px">
                        <ItemTemplate>
                            <asp:Button ID="Button2" runat="server" Text="Copy" />
                        </ItemTemplate>
                    </asp:TemplateField>
   
    </Columns>

    </asp:GridView>

<!--------------------------JavaScript-------------------------------------------->

 <script type="text/javascript">
            function CopyGridView(target) {
                var div = document.getElementById(target);
                div.contentEditable = 'true';
                var controlRange;
                if (document.body.createControlRange) {
                    controlRange = document.body.createControlRange();
                    controlRange.addElement(div);
                    controlRange.execCommand('Copy');
                }
                div.contentEditable = 'false';
                return false;
            }
    </script>

<!------------------C# code behind--------------------------------------------->
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl1 = e.Row.FindControl("Label1") as Label;
            Button btn1 = e.Row.FindControl("Button1") as Button;
            btn1.Attributes.Add("onclick", "return CopyGridView('" + lbl1.ClientID + "')");
       
            Label lbl2 = e.Row.FindControl("Label2") as Label;
            Button btn2 = e.Row.FindControl("Button2") as Button;
            btn2.Attributes.Add("onclick", "return CopyGridView('" + lbl2.ClientID + "')");
        }
    }
0
 

Author Closing Comment

by:forsters
Comment Utility
The solution that ultimately worked for me was without doubt thanks to the experts help, but for anyone else trying to follow this, the actual working solution is in my post hence why I have indicated that as being the solution. Hope someone finds it helpful.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now