Set focus and cursor at end of text?

O

Olav Tollefsen

I use this code to set focus to a textbox when I load a page:

private void SetFocus(System.Web.UI.Control ctrl)
{
string s = "<SCRIPT language=\"javascript\">document.getElementById('" +
ctrl.ID + "').focus()</SCRIPT>";

RegisterStartupScript("focus", s);
}

I would also like the cursor to be positioned at the end of the text field.
Using only the above code, the cursor is positioned at the beginning of the
textbox even if there are some text present in the field.

How can I position the cusrsor at the end of the text?

Olav
 
M

Mohammad A. Samara

Olav,

Here we go:

Create a new function in your <head> tag in the HTML section:

function SetEnd (TB)
{
if (TB.createTextRange)
{
var FieldRange = TB.createTextRange();
FieldRange.moveStart('character', TB.value.length);
FieldRange.collapse();
FieldRange.select();
}
}

Create a new onfocus JavaScript event in your asp text box tag (asp:textBox)
that calls the SetEnd function above:

<asp:textbox id="TextBox1" runat="server" Width="65px"
onfocus="SetEnd(this)">Existing text</asp:textbox>

Make sure you keep your existing code that calls the SetFocus function as it
is:

private void SetFocus(System.Web.UI.Control ctrl)
{
string s = "<SCRIPT language=\"javascript\">document.getElementById('" +
ctrl.ID + "').focus()</SCRIPT>";

RegisterStartupScript("focus", s);
}

Don't forget to call the above SetFocus() function in your Body tag on page
load .....( <body onload="SetFocus()"> )

Good luck!

Regards,

Mohammad Samara.

ICS (London) Ltd.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top