How can I set the textbox focus to the end of the text after a postback?

In my ASP.Net form, there is a text box and a button. When the user clicks the button, it adds text to an ASP:TextBox during a postback (it adds a specific "starter text"). After the postback, I want the focus to be set to the end of the text in the textbox.

When I try to call Page.SetFocus(...) or txtBox.Focus(), the text box gets focused but at the beginning of the text. This can lead to the user typing in the wrong place.

For example:
cursor100-01

I would like it to appear as:
100-01cursor

I attempted the following code in the textbox:

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

However, the "alert" only shows up the first two times. After that, nothing happens.

Answer №1

After doing some research, I stumbled upon a helpful solution on the asp.net website. It's worth checking out for more discussions on the cross-browser version of this solution!

Here is the JavaScript code that accomplishes the task:

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS is patiently anticipating the population of the scope for ng-show

I have implemented ng-show to display an error message based on an array. The code I used is ng-show="!items.length". However, since the items are populated after a request, there is a flickering effect for a brief moment before the items are loaded. Is th ...

Tips for creating a blur effect on all options except for the selected 2 out of 4 using jQuery

My goal is to choose 3 options from a list and once 3 options are selected, all other options will be blurred to prevent further selection. Please review the code snippet I have provided below. Link to File <!DOCTYPE html> <html> <head> ...

What is the proper way to connect my JavaScript code to my HTML form?

My JavaScript function is not working properly when I try to submit a form on my website. <form onsubmit="validateRegistration()"> <p> // Email registration <input type="text" id="e-mail" placeholder="Email" /> </p> ...

What is the process for selectively adding interceptors to app.module?

After searching through various topics, I have not found a solution that addresses my specific issue. To provide some context, we have an Angular App that operates in two modes - one mode uses one API while the other mode utilizes a different API. My goal ...

"Figuring out a way to include a link with each image in a react-s

I am currently working on a project in Gatsby and encountering some issues with the homepage banner. I am using react-slick which seems to be functioning fine, but when I try to add content on top of each image, it causes some problems. Specifically, setti ...

Instant data entry upon clicking

In an attempt to automate input based on image pairs, I encountered a challenge. On one side, there are two images that need to be matched with input fields, and on the other side, there are corresponding letters for each image to fill in the inputs upon c ...

Converting a GET request from Entity Framework to a GET request without using Entity Framework

I have been learning ASP.NET MVC & Angular through an online tutorial, but the author, Sourav Mondal, uses Entity for database querying. Unfortunately, I am working with SQL Server 2000 and EF is not feasible in this context. Below is the code snippet that ...

The justify-between utility in Tailwind is malfunctioning

Can someone help me figure out how to add justify-between between the hello and the user image & name? They are in different divs, but I've tried multiple ways without success. I'm fairly new to this, so any advice would be appreciated. This ...

Prevent Cordova from shrinking the view when focusing on an input

Currently working on developing an app using Cordova/Phonegap (v6.5.0). Platforms where I've installed the app: - IOS (issue identified) - Android (issue identified) - Browser (no issue found) I am facing a known problem without a suitabl ...

What is the best way to customize the CSS of the Skype contact me button?

I am struggling with customizing the Skype contact me button. The standard Skype button has a margin of 24px and vertical-align set to -30px. I have tried removing these styles but have had no success. Here is the code snippet I am working with: Skype ...

Engaging with tasks like incorporating fresh elements into JavaScript code

I am looking to implement an event listener that triggers whenever a new element is added to the document or any of its children. Can someone recommend a method for accomplishing this? ...

Discover additional Atom extensions

I am exploring the possibility of implementing a feature in my Atom package where it can automatically detect whether specific third-party packages have been installed. Currently, my package adds configuration for one such third-party package, but I want t ...

The ApexChart Candlestick remains static and does not refresh with every change in state

I am currently working on a Chart component that retrieves chart data from two different sources. The first source provides historic candlestick data every minute, while the second one offers real-time data of the current candlestick. Both these sources up ...

Removing an active image from a bootstrap carousel: A step-by-step guide

Within my bootstrap carousel, I have added two buttons - one for uploading an image and the other for deleting the currently displayed image. However, I am unsure how to delete the active element. Can someone provide assistance with the code for this but ...

Utilize JavaScript or jQuery to segment HTML elements

Looking for a front-end solution to a common practice. In the past, I've stored reusable HTML elements (such as <nav>, <header>, <footer>, etc.) in a functions.php file and used PHP functions to include them on multiple pages. This ...

Error encountered in Node/Express application: EJS partials used with Angular, causing Uncaught ReferenceError: angular is not defined

I seem to be missing something important here as I attempt to incorporate ejs partials into a single-page Angular app. Every time I try, I encounter an Uncaught ReferenceError: angular is not defined in my partial. It seems like using ejs partials instead ...

Creating smooth animations in JavaScript without relying on external libraries such as jQuery

Is there a way in JavaScript to make a <div> slide in from the right when hovered over, without relying on jQuery or other libraries? I'm looking for a modern browser-friendly solution. const div = document.querySelector('.fro ...

Display the current time and continuously update it in real-time on the DOM using React

Incorporating a live clock feature into my app is important to me. I want the time to update automatically, without requiring the user to manually refresh the page. My goal is to have a clock display the time, for example 11:59, and then transition to 12: ...

"The Ajax function for replacing a div upon change event is not functioning properly

I am having an issue with my select box using the onchange event, <select class="form-control" onchange="getval(this.value,'<?php echo $prd->pr_id;?>','ajax<?php echo $key?>','<?php echo $key ?>')"&g ...

What is the best way to extend a model through subclassing and then persist the extra information?

In my application logic, I have chosen to create subclasses for different types of users in the following way: public class User { public string eRaiderUsername { get; set; } public int AllowedSpaces { get; set; } public ContactInformation Con ...