New to Telerik UI for ASP.NET Core? Download free 30-day trial

Copy Text from TextBox to Clipboard

Environment

Product Telerik UI for ASP.NET Core TextBox
Product Version 2024.1.130

Description

How can I copy text from the TextBox component directly within the Clipboard?

Solution

To achieve the desired result:

  1. Utilize the TextBox's SuffixOptions() configuration and define a template.
  2. Within the template, create a Button component and wire to its Click event.
  3. Within the event handler, use the Clipboard interface's writeText() method to copy the text from the TextBox.
     @(Html.Kendo().TextBox()
        .Name("email")
        .Label(l => l.Content("Email Address").Floating(false))
        .Value("test@mail.com")
        .SuffixOptions(suffix => suffix
             .Template(Html.Kendo().Template()
                .AddComponent(component => component
                    .Button()
                    .Name("copyBtn")
                    .Icon("copy")
                    .Events(events => events.Click("onClick"))
                )
             )

        )
        .HtmlAttributes(new { style = "width: 100%;", type = "email" })
    )
    <script id="buttonTemplate" type="text/html">
        <kendo-button name="copyBtn"
                      icon="copy"
                      on-click="onClick"
                      is-in-client-template="true">
        </kendo-button>
    </script>

    <kendo-textbox name="email" type="email">
        <suffix-options template-id="buttonTemplate" />
    </kendo-textbox>
    <script>
        function onClick(e){
            var textBoxValue = $("#email").getKendoTextBox().value();
            navigator.clipboard.writeText(textBoxValue);
        }
    </script>    

To see an extended example of the aforementioned approach, refer to the following Telerik REPL example:

More ASP.NET Core TextBox Resources

See Also

In this article