AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1109&pId=-1
CodeSnip: Inserting Text at Cursor Location Using JavaScript
page
by Pallavi Mahure
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 26583/ 38

Introduction

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>
Downloads
Conclusion

In this article we demonstrated how another text can be inserted into the cursor position of TextBox control in ASP.NET using JavaScript. To use this code, a user can just open a new ASP.NET page and on the HTML side just paste the above code and run it.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-25 6:35:21 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search