It is always nice if we can insert some text at the cursor
location in Textbox from some other Textbox. Consider the scenario, suppose you
have TextBox1 and TextBox2. Now you want to paste some text from Textbox2 to
TextBox1 through program. So, either the text in TextBox1 will be overwritten
or the new text will be appended at the end of text. If you want text to be
inserted at cursor location of TextBox1, then the following code will help you.
JavaScript function is used to accomplish it. It is called an onClick event
of button. JavaScript function Show () is registered with ASP.NET command
button on page load.
ASPX Code
Listing 1
Private Sub Page_Load(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CmdButton.Attributes.Add("onClick", _
"Show()")
End Sub
JavaScript Code
Listing 2
<a name="_HTML_SECTION"></a><script language = "java-script">
function Show()
{
var ctrl =
document.getElementById("txtTargetText");
var saveText = ctrl.value;
ctrl.focus();
var range = document.selection.createRange();
var specialchar = String.fromCharCode(1);
range.text = specialchar;
var pos = ctrl.value.indexOf(specialchar);
ctrl.value = saveText;
range = ctrl.createTextRange();
range.move('character', pos);
range.select();
range.text =
document.getElementById("txtSourceText").value;
document.getElementById("txtTargetText").focus();
window.event.returnValue = false;
}
</ script>
HTML Section
Listing 3
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox id="txtTargetText" style="Z-INDEX: 101; LEFT:
136px; POSITION: absolute; TOP: 40px" runat="server"
Width="489px"></asp:TextBox>
<asp:Button id="cmdButton" style="Z-INDEX: 102; LEFT: 320px;
POSITION: absolute; TOP: 144px" runat="server"
Text="Button"></asp:Button>
<asp:TextBox id="txtSourceText" style="Z-INDEX: 103; LEFT:
280px; POSITION: absolute; TOP: 88px" runat="server"
Width="168px" Height="32px"></asp:TextBox>
</div>
</form>
</body>