Copy the text in a textbox on click
Tuesday, November 25, 2008
This is a simple Javascript to copy the text in a textbox in an aspx page. Suppose we have a textbox defined as follows
Now add an attribute to the textbox. This attaches the clientside event 'onClick' to the textbox.
The function, 'copySelectedCode()' is defined in the <script> </script> section.
On clicking the textbox, the text in the textbox is selected and copied. Also a messagebox is shown saying the code is copied.
NOTE:'execCommand()' is the command used to execute a command on the current document, current selection, or the given range. To know execCommand commands visit MSDN.
<asp:TextBox ID="txtCode" runat="server" TextMode="MultiLine" ReadOnly="True" Height="63px" CssClass="client" Width="325px"></asp:TextBox>
Now add an attribute to the textbox. This attaches the clientside event 'onClick' to the textbox.
txtCode.Attributes.Add("onclick", "copySelectedCode();");
The function, 'copySelectedCode()' is defined in the <script> </script> section.
<script type="text/javascript">
function copySelectedCode()
{
var txt=document.getElementById('txtIFrameCode');
if(txt.value!='')
{
txt.select();
txt.focus();
txt.createTextRange().execCommand("Copy");
alert('Code copied');
}
}
</script>
On clicking the textbox, the text in the textbox is selected and copied. Also a messagebox is shown saying the code is copied.
NOTE:'execCommand()' is the command used to execute a command on the current document, current selection, or the given range. To know execCommand commands visit MSDN.
Labels: ASP.NET, C#, Code, DOTNET, Javascript