Managing Cursor Position upon Form Field Focus

I need assistance with a form that has 4 fields. I would like the first field to have the autofocus so it is the first one the user fills out. However, when the user navigates to the second field, whether by tab or mouse, I want the cursor to automatically move to the end of the string in that field. The field contains a pre-filled string.

I am using Django and have a form widget controlling the attributes. I've been able to display the string and move the cursor to the end, but this also triggers the autofocus on the second field. I haven't been able to achieve both functionalities simultaneously.

Here is the code I have implemented:

Django

field = forms.URLField(
    widget = forms.URLInput(
        attrs = {
            'placeholder': 'enter field',
             # call to javascript function - this works
            'onfocus': 'add_string("field_id", "string")',
        } 
    )
)

JavaScript:

// add string to element
function add_string(id, string) {
    var input = document.getElementById(id);
    input.value = string;
}

I have experimented with various JavaScript scripts without success. Then, I discovered setSelectionRange and tried incorporating it like this:

input.setSelectionRange(7, 7)

Where 7 represents the end of the specific "string" in the onfocus JavaScript function call, but unfortunately, I couldn't get it to work...

Lastly, I tried utilizing some jQuery code like this:

// focus after string, no highlight
$(document).ready(function() {
    var $field = $("#field_id");
    var old_val = $field.val();
    $field.focus().val('').val(old_val);
});

However, this resulted in the same outcome: initial focus on the second field and the cursor moving to the end.

Do you have any suggestions on how I can achieve both autofocus on the first field and have the cursor jump to the end of the pre-filled string in the second field upon its focus? It would be a neat trick if I could figure out how to accomplish this.

Answer №1

Just a little further to go! Make sure to trigger your code when the form field is in focus, rather than waiting for the document to be ready. In my own experiments, I found it helpful to introduce a slight delay of zero milliseconds to ensure the field value is deselected:

$(document).ready(function() {
    var $field = $("#field_id");
    $field.on('focus', function() {
        setTimeout(function() {
            var old_val = $field.val();
            $field.val('').val(old_val);
        }, 0);
    });
});

Check out this JSFiddle demo!

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

Listen for events in a child process in NodeJS

I am currently utilizing the node child_process API https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options var child = child_process.spawn(cmd, val, options); Within the child process, I make use of the followin ...

Invalid WebResource with broken links

Within our internal network, the website functions smoothly without any issues. However, when trying to access the same site from an external location, we encounter a specific error message at the end of the WebResource.axd return: /* START */ /* Skipped ...

Utilizing JavaScript for simulating key presses on a webpage

Is it possible for a website to detect keystrokes and mouse movements? Can JavaScript be used to simulate actions, like clicking a mouse button, without physically doing so? If my question is unclear, please let me know. I'm new to this and feeling a ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...

Filter out discord messages for deletion

A script was created to automatically delete messages from offline users during chat sessions on Discord. If an offline user attempted to chat, their message would be deleted, and a notification would be sent to the console indicating that offline chat was ...

What are the steps to kick off my React App once I've cloned it?

Currently grappling with deploying my app using Netlify, I encountered an issue after cloning the app onto my new computer. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afee5eee5e6e3f9fefcb8cabba4baa4ba">[email  ...

Utilize AJAX without jQuery to toggle between different content displayed on the index page and the login page

One issue I am facing is with the setup of my index.php page, which contains a sign-up form and a switch button. The button triggers an ajax request to fetch content from login.php and updates the form. However, I'm encountering difficulties when tryi ...

Utilizing Angular's ng-repeat with varying directives for each iteration

I am trying to utilize ng-repeat within Angular to iterate through multiple <li> elements with a directive embedded. My goal is to have the first two items in the ng-repeat display differently in terms of styling and content compared to the remaining ...

Identifying the action of maximizing a window using JavaScript

Similar Question: How to Detect if a Browser Window is Maximized or Minimized using Javascript Can we use javascript to identify when the browser window is maximized? ...

The form validation feature in Element UI is having issues when used with the Vue 2 Composition API

I am currently developing a form that utilizes element UI's form validation within the vue 2 composition API environment. This form includes a table nested inside, making its structure somewhat complex. ... <div> <el-form ref=" ...

Learn how to properly retrieve a form variable in a Django template

Exploring the utilization of feedback forms within my app has brought me to the creation of a FeedBack model and a corresponding FeedBackForm. models.py: class Feedback(models.Model): name = models.CharField(max_length=150, blank=True) email = models.Ema ...

Tips for implementing JS function in Angular for a Collapsible Sidebar in your component.ts file

I am attempting to collapse a pre-existing Sidebar within an Angular project. The Sidebar is currently set up in the app.component.html file, but I want to transform it into its own component. My goal is to incorporate the following JS function into the s ...

Seeking guidance on capturing the correct error message when using JSON stringify?

Imagine I have an object structured as follows var obj = { "name": "arun" age } After attempting JSON.stringify(obj), it results in an error due to the improper structure of the obj. I am interested in capturing this error displayed in the console and pr ...

How to efficiently transfer dynamically generated table row data to JavaScript for database submission using the POST method

Currently, I am working with Laravel and facing an issue related to dynamic rows in my form. Each row has its own form with unique values. My goal is to pass the form data along with values to JavaScript when the submit button is clicked without refreshin ...

Disabling the ripple effect on the primary action in React Material lists: A Step-by-Step

I was attempting to include two action buttons at the opposite ends of a list component. https://i.stack.imgur.com/juv8F.gif When clicking on the secondary action (delete icon on the right), the ripple effect is confined to just the icon. On the othe ...

Capturing the clicked element within a Vue (JS) instance by utilizing $(this) can be achieved by following these

I'm currently revamping an older application of mine and running into challenges with DOM manipulation and basic selections within a Vue instance. The data in my database is loaded via AJAX and each record consists of two parts: the header tab (title ...

Accessing loop variables in Render and passing them into componentDidMount() in ReactJS to include as a query parameter in an API call

Within the render function, I am using a loop to rotate an array of coordinates in order to position markers on a map. {coords.map(({ lat, lng }, index) => (code goes here and so on))} I intend to replace query parameters with the variable generated f ...

The fancybox's excess content is concealed

I've recently integrated fancybox 2 into my project and have encountered an issue when appending HTML content to the modal. I disabled scrolling, but now any overflowing content is being hidden. Could this be related to the max-height of the modal? Ho ...

Django: Struggling with Constant CSRF Verification Failures

When attempting to perform a POST action from my frontend to separate frontend and backend servers, I include a "Cookie" header with csrftoken inside, but it doesn't seem to be working. I even tried passing the csrftoken alone in the header, but encou ...

Looking to include a sub element in my menu items using jQuery and CSS

Using jQuery and CSS, I have created a menu item. How can I navigate from one menu item to another sub menu item, as illustrated in the image below? Below is my HTML markup: <link rel="stylesheet" href="css/style_j.css" type="text/css" media="screen"/ ...