views:

26

answers:

1

I've got a simple ASP.Net form with txtBox and btn.
User click btn, which adds text to an ASP:TextBox in a postback (its adding a known "starter text".
After the postback I'd like the focus to be set to the end of the text in the textbox.

If I call Page.SetFocus(...) or txtBox.Focus() then the txtBox gets focus, but at the beginning of the text - which means if the user starts typing, they'll be in the wrong place.

e.g.
cursor100-01

would like it to be

100-01cursor

I've tried the following in the textbox:

onfocus="alert('focus');this.value = this.value;"

but the "alert" only appears the first two times? Then nothing?

A: 

I found a solution in asp.net website ( check it for discussion about cross browser version of given solution!)

there is javascrip code that do it:

<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', text.value.length);
                    FieldRange.collapse();
                    FieldRange.select();
                }
            }
        }
</script>
zgorawski
How do I call that from the postback though?
BlueChippy
I would pin this function onto onFocus event handler, like in yours example.
zgorawski