Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Move Cursor to End of Textbox

Status
Not open for further replies.

Silo4

Programmer
Nov 7, 2002
17
GB
Hi,

I've been pointed in the direction of the Javascript forum to answer a question i posted on the ASP.NET forum. I found a similar post in this forum titled "Set cursor to the end of a textbox ?????" and i think the solution could work, but I have absolutely no experience with Javascript and the solution does not explain what to do. Can someone help?

Here's my original question.

I am using a button to insert a string into a textbox on my webform. I want the cursor position to be set to the end of the inserted text so the user can continue typing without having to manually reposition the cursor.

In a VB.NET windows form i'd use...

TextBox1.Text = "Hello World"
TextBox1.Focus()
TextBox1.SelectionStart = TextBox1.Text.Length

I can insert the text and focus back onto the textbox, but when the textbox recieves focus the cursor is reset to the start of the text.

Does anyone know how i can set the cursor to the end in ASP.NET?

Thanks
 
Should be fair to Silo4. Was sent over to javascript forum from there!
 
It's taken a while but i've finally figured it out. I've built it into a VB.NET function for use in ASP.NET. Cut and paste below and simply call the function.

Silo4

Sub SetCaretPosToEnd(ByVal ctrl As Control)
Dim sb As New System.Text.StringBuilder("")
With sb
.Append("<script language='JavaScript'>")
.Append("function GetCaretPos ()")
.Append("{")
.Append("var MyControl = ")
.Append("document.")
.Append(ctrl.Parent.ID)
.Append("['")
.Append(ctrl.UniqueID)
.Append("'] ;")

.Append("if (MyControl.createTextRange)")
.Append("{")
.Append("var range = MyControl.createTextRange();")
.Append("range.collapse(false);")
.Append("range.select();")
.Append("}")
.Append("else if (control.setSelectionRange)")
.Append("{")
.Append("var range = MyControl.createTextRange();")
.Append("range.collapse(false);")
.Append("range.select();")
.Append("}")
.Append("}")
.Append("window.onload = SetCaretPosToEnd;")
.Append("</script")
.Append(">")
End With
ctrl.Page.RegisterClientScriptBlock("SetCaretPosToEnd", sb.ToString())
End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top