Regain the cursor focus on a text input field once it has been disabled and re-enabled using AngularJS

In my code, I have implemented an input field along with a $watch function that triggers a server request when the scope variable changes. While the server request is being processed, I disable the input field. However, once the request is complete and the field is re-enabled, the cursor is missing from the input line. I want to ensure that the cursor is present again when the input field is enabled.

I attempted to restore focus using a directive such as How to set focus on input field?, but unfortunately, it does not seem to work in conjunction with enabling/disabling the field. I tried setting both the "focusing" and "enabling" variables at the same time, but it did not have the desired effect.

Answer №1

implement a custom directive for focusing

app.directive('focusMeDirective', function($timeout) {
  return {
    scope: {
      trigger: '=focusMeDirective'
    },
    priority: -1,
    link: function(scope, element) {
      scope.$watch('trigger', function(value) {
        if (value === true) {
          $timeout(function() {
            element[0].focus();
            scope.trigger = false;
          }, 300);
        }
      });
    }
  };
});

include the directive in the input field

<input type="text" focus-me-directive="focusInput" data-ng-model="myModel" required .. />

in the controller

$scope.focusInput=true;

when $scope.focusInput is set to true, the input field will receive focus

Answer №2

Simple method

<input type="text" ng-disabled="true" required ... />

Following an event, if you wish to enable and focus on the input field, you can achieve this functionality by adding the following code to your .ts file

$scope.enableInput = function () {
  document.getElementById("password").disabled = false;
  document.getElementById('password').focus();
};

This is how you can re-establish focus on the text input field after toggling its disable and enable states using AngularJS

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

Failed to load JSON data from the factory

Recently, I started learning AngularJS and have been struggling to fetch JSON data from a factory. The error message I keep getting is not very helpful: TypeError: Cannot read property '1' of null This is the module I am working with: var app ...

What is the method for sending these variables via POST?

The code snippet referred to as New script is designed to produce two integer variables anchor and signed. I am interested in replacing the Old script with the New script, but there are significant differences between them. Inquiry How can I send/post t ...

Leveraging an external global variable file that is not incorporated into the bundle

I have a JavaScript file dedicated to internationalization. I am looking for a way to provide this file to clients for them to edit without requiring me to rebuild the entire project. Currently, I store this file in the static folder so it is included in ...

On mobile devices, the code "location.assign(url)" may occasionally redirect to an incorrect URL, despite functioning correctly in the majority of instances

After setting up a page with a timeout that should automatically redirect to a specific URL after 60 minutes, I encountered an issue where the redirection sometimes leads to a loss of parameters in the URL. The JavaScript code added for this purpose is set ...

How can I toggle the visibility of a div based on whether a variable is defined or not?

How can I display a specific div on my webpage only when certain variables in PHP pull out a specific result from a database? I attempted to use the code snippet below, but it's not working as expected. Can someone provide guidance on how to achieve ...

Passing a JavaScript object that may be undefined to a pug template in Node.js

My journey requires transferring a set of JavaScript objects to the pug template. router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeE ...

Issue with executing Jquery in PUG file: The $ sign is not being recognized despite jQuery being imported

I am encountering an issue where my jQuery code placed inside a pug template is not executing as expected. Despite including the jQuery file, when trying to run a jQuery function, I receive the error below: 40| P 41| ...

Tips for updating the value of the most recently created div in an ng-repeat loop

Within my HTML document, the following code is present: <div ng-repeat="selection in selections" style="margin-left:{{marginLeft}}%;width:{{progress}}%;background-color:{{selection}}"> </div> In my controller, I have implemented function ...

When combining Socket.io 1.0 with express 4.2, the outcome is a lack of socket connection

According to the title, I am attempting to integrate socket.io 1.0.4 with express 4.2, but all requests with "/?EIO" are resulting in a 404 error. Below are my file configurations: ./bin/www : #!/usr/bin/env node var debug = require('debug')(& ...

What is the best way to calculate the total of a field with matching Project and Employee names?

My task involves grouping data from an Array of objects by Project Name and Employee Name, whereby existing projects and employees have their hours added together. projects = [ { "project": { "id": 1, "name": "M ...

I am having trouble importing Material UI icons. Can anyone guide me on how to successfully use Material UI icons without any

While working on my project with React and Material UI, I encountered some difficulties when trying to import the material icons. I followed the code examples from the Material UI documentation, using version "material-ui": "^1.0.0-beta.41" and "material-u ...

Issues with Autofocus while Searching and Selecting from Dropdown menu

Here is the JavaScript code I am using: <script type="text/javascript"> function handleSelectionChange(selectElement, nextField) { nextField.focus(); } function handleKeyPress(event, currentField, nextField) { i ...

When working with the Google Sheets API, an error occurred: "this.http.put(...).map is not a valid

Having difficulty with a straightforward request to the Google Sheets API using the PUT method. I followed the syntax for http.put, but an error keeps popping up: this.http.put(...).map is not a function. Here's my code snippet: return this.http ...

Unable to display the attributes of an object using console.log

I am attempting to log the properties of an object in TypeScript, but I am encountering issues. setTitleAndBody(result: { title: String; body: String; }) { console.log(result) console.log(result.title) } What's interesting is that if I only l ...

What is the best way to determine if an item in an array is not empty?

Let's consider an array: arr = [{}, {}, {}, {}] If we want to determine the length of the array by counting only objects that contain at least one property, we can do this: [{}, {name: "Manchester United", odds: 3}, {}, {}] // 1 [{}, {name: "Liver ...

The issue persists with the addEventListener function not working multiple times

My issue is that the addEventListener function is only working for the 'scroll' event and not for 'addMoreFields' or 'removeFields'. If I move the scroll section down, then it works for 'addMoreFields' and 'remo ...

Creating a custom function in a Node.js application and rendering its output in the front-end interface

I've been trying to scrape data from a website and display it using innerHTML, but I'm running into some issues. The code snippet I'm using is: document.getElementById('results').innerHTML = searchJobs(''); However, I ke ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Looking for a drag-and-drop solution using Vanilla Javascript, no need for jQuery

Looking for assistance with creating a click-and-drag solution for a background image using Vanilla Javascript. I came across a jQuery solution on Codepen, but I need help translating it into Vanilla Javascript. Draggable.create(".box", { ...

Leveraging orWhere in the bookshelf JavaScript object

I encountered an issue while using bookshelf js to create a query. When implementing orWhere in the query, I received an error message. An error occurred stating 'Object has no method 'orWhere'." Below is the code snippet that led to thi ...