Search code examples
javascriptc#jqueryasp.netrepeater

How to select the text from my textbox inside a repeater using Jquery?


I have a repeater and inside of it is a textbox that contains my data from the database. Of course at run-time it will generate lots of data meaning lots of textboxes too.

<asp:Repeater ID="rpter" runat="server">
  <ItemTemplate>
    <fieldset>
      <legend>
        <asp:Label ID="lblLegend" runat="server" Text='<%#DataBinder.Eval(Container,"DataItem.Name")%>' Font-Bold="true" />
      </legend>
      <div style="border: single, 1px;">
        <div>
          <asp:TextBox ID="txtMessage" runat="server" Text='<%#DataBinder.Eval(Container,"DataItem.Message")%>' Width="100%" TextMode="MultiLine"></asp:TextBox>
        </div>
       <div>
         <asp:Button ID="btnCopy" runat="server" Text="Copy" CommandName="Copy" OnClientClick="copyClipboard()" />
         </div>
      </div>
    </fieldset>
  </ItemTemplate>
</asp:Repeater>

What I want is to select the text from the textbox besides the copy button when I clicked the button so that I can copy it on clipboard..

function copyClipboard() {
    CopiedTxt = document.selection.createRange();
    CopiedTxt.execCommand("Copy");
}

Solution

  • I have to edit your ASP code and add CssClass="txtMessage" to the TextBox.
    Also CssClass="btnCopy" to the Button
    And removed the OnClientClick="copyClipboard()" because we will handle that in our jQuery as below:

    ASP:-

    <asp:Repeater ID="rpter" runat="server">
        <ItemTemplate>
        <fieldset>
            <legend>
            <asp:Label ID="lblLegend" runat="server" Text='<%#DataBinder.Eval(Container,"DataItem.Name")%>' Font-Bold="true" />
            </legend>
            <div style="border: single, 1px;">
                <div>
                    <asp:TextBox ID="txtMessage" runat="server" CssClass="txtMessage" Text='<%#DataBinder.Eval(Container,"DataItem.Message")%>' Width="100%" TextMode="MultiLine"></asp:TextBox>
                </div>
                <div>
                    <asp:Button ID="btnCopy" runat="server" CssClass="btnCopy" Text="Copy" CommandName="Copy" />
                </div>
            </div>
        </fieldset>
        </ItemTemplate>
    </asp:Repeater>
    

    Don't forget to include jQuery library:

    <script type="text/javascript" src="jquery-1.10.2.min.js"></script>
    

    And the jQuery will handle all clicks to any item with class of btnCopy and look for .txtMessage item inside the parent of the parent of the button
    And select the text inside that TextBox
    And return false so your click won't take you any where...

    jQuery:-

    $(function () {
        $(".btnCopy").click(function (e) {
            $(this).parent().parent().find(".txtMessage").select();
            return false;
        });
    });
    

    I wish that will work for you and this is the screenshot:
    http://i59.tinypic.com/5ujvc9.jpg
    http://i62.tinypic.com/35d4y7l.jpg

    Good luck ;)