4

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?

BlueChippy
  • 5,935
  • 16
  • 81
  • 131
  • Plaese don't repost the same question: http://stackoverflow.com/questions/4033141/set-focus-in-textbox-after-postback You can always edit your question. Have a look at this thread for more informations: http://meta.stackexchange.com/questions/7046/how-to-get-attention-for-your-old-unanswered-questions – Tim Schmelter Oct 27 '10 at 13:44

1 Answers1

4

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
  • 2,597
  • 4
  • 30
  • 43