Monday, January 21, 2008

Javascript - Textbox cursor position at last while focusing

Create a new function in your 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:

Existing text

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 = "
";

RegisterStartupScript("focus", s);
}

Don't forget to call the above SetFocus() function in your Body tag on page
load .....( )