Wednesday, June 3, 2009

Place Cursor after some character in a Textbox

In one of my project requirement was to Place Cursor after some character in a Textbox.
because their was a textbox (lets say txtPhoneNo).The initial value of txtPhoneNo is (868).Now i will have to place the cursor after (868) whenever user will click on that textbox.
This is very interesting thing
I do this by writting a javascript function......

<script type="text/javascript">
function SetCursorToTextEnd(textControlID)
{
var text = document.getElementById(textControlID);
if (text != null && text.value.length > 0)
{
if (text.createTextRange)
{
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', 5);
FieldRange.collapse();
FieldRange.select();
}
}
}
</script>
Write this line in Page_Load of aspx.cs file
txtPhoneNo.Attributes.Add("onfocus", "javascript:SetCursorToTextEnd(this.id)");